Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export DataTable to Excel File

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

like image 867
Vix Avatar asked Nov 17 '09 05:11

Vix


People also ask

How do I export DataTable to Excel?

You can turn a DataTable into an Excel worksheet with some very readable code: XLWorkbook wb = new XLWorkbook(); DataTable dt = GetDataTableOrWhatever(); wb. Worksheets. Add(dt,"WorksheetName");

How do I add the export button to a DataTable in Excel?

You need to simply add below javascript cdn to add export button in datatable. Add below javascript code in your script tag. $(document). ready(function() { $('#export_example').


1 Answers

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(); 
like image 57
Muhammad Akhtar Avatar answered Sep 20 '22 14:09

Muhammad Akhtar