views:

728

answers:

2

Hi, I have a DataTable with 30+ columns and 6500+ rows.I need to dump the whole DataTable values into an Excel file.Can anyone please help with the C# code.I need each column value to be in a cell.To be precise,I need the exact looking copy of DataTable in an Excel File.Please help.

Thanks, Vix

+1  A: 

You could try the technique described here:

C-Sharp Corner

Randolpho
I need code to export data from datatable to excel.The link above explains exporting data from a gridview.That doesn't serve my needs.Could you please help??
Vix
+2  A: 

use this code...

    dt = city.GetAllCity();//your datatable
    string attachment = "attachment; filename=city.xls";
    Response.ClearContent();
    Response.AddHeader("content-disposition", attachment);
    Response.ContentType = "application/vnd.ms-excel";
    string tab = "";
    foreach (DataColumn dc in dt.Columns)
    {
        Response.Write(tab + dc.ColumnName);
        tab = "\t";
    }
    Response.Write("\n");
    int i;
    foreach (DataRow dr in dt.Rows)
    {
        tab = "";
        for (i = 0; i < dt.Columns.Count; i++)
        {
            Response.Write(tab + dr[i].ToString());
            tab = "\t";
        }
        Response.Write("\n");
    }
    Response.End();
Muhammad Akhtar
Thanks a lot Akhtar.It solved my purpose and I've my excel copy ready.
Vix
Of all the convoluted articles I came across on the web to accomplish this it was nice to find a short, simple solution that just works. Many thanks!
brian newman
Any suggestions to force Excel to treat all fields as string regardless of the data? For example, do not drop the leading zeros in '0000012'. I tried prefixing the values with an apostrophe but the apostrophe showed up in the spreadsheet.
brian newman