Click here to Skip to main content
15,886,518 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In the following I am unable to send all the rows of datatable 'dttxfile' to an excel file.
Only one row is sent. How to send all rows?

System.Data.DataTable dttxfile = new System.Data.DataTable();
da2.Fill(dttxfile);
DataColumnCollection dcCollection = dttxfile.Columns;
Microsoft.Office.Interop.Excel.ApplicationClass ExcelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
ExcelApp.Application.Workbooks.Add(Type.Missing);
for (int j = 1; j < dttxfile.Columns.Count + 1; j++)
{

ExcelApp.Cells[ii, j] = dcCollection[j-1].ToString();
ExcelApp.Cells[ii + 1, j] = dttxfile.Rows[ii - 1][j - 1].ToString();
}
Posted

1 solution

You need a loop for your rows :
C#
System.Data.DataTable dttxfile = new System.Data.DataTable();
da2.Fill(dttxfile);
DataColumnCollection dcCollection = dttxfile.Columns;
Microsoft.Office.Interop.Excel.ApplicationClass ExcelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
ExcelApp.Application.Workbooks.Add(Type.Missing);
for(int ii=1 ; ii< dttxfile.Rows.Count+1; ii++) // add this line
for (int j = 1; j < dttxfile.Columns.Count + 1; j++)
{
if(ii==1) // add this
ExcelApp.Cells[ii, j] = dcCollection[j-1].ToString();
ExcelApp.Cells[ii + 1, j] = dttxfile.Rows[ii - 1][j - 1].ToString();
} 
 
Share this answer
 
v2
Comments
S.Rajendran from Coimbatore 8-Feb-14 3:46am    
SqlDataAdapter da2 = new SqlDataAdapter("select Carttxno from txfile where carttxno='" + v_carttxno + "'", sqlCon);
It works but the excel file has the column name 'Carttxno' of the table in all the 3 rows instead of values of the column 'carttxno'.
In my table 'txfile' I have 3 rows with values '341' in all the 3 rows. As per the code the excel file looks like this:
carttxno
carttxno
carttxno
341
Whereas it should look like:
341
341
341
S.Rajendran from Coimbatore 8-Feb-14 3:49am    
in the datatable 'dttxfile' the 3 rows are perfect and looks like.
341
341
341
Mehdi Gholam 8-Feb-14 3:52am    
See the edited solution.
S.Rajendran from Coimbatore 8-Feb-14 4:21am    
Thanks. It works.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900