Hi,
I have data in a Data Table. Now I need this data to written in Excel File 2003 . I need to create a New File and Write the Data and close the file.
I need the code. Please help me.
Regards,
Mzee
Hi,
I have data in a Data Table. Now I need this data to written in Excel File 2003 . I need to create a New File and Write the Data and close the file.
I need the code. Please help me.
Regards,
Mzee
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Santhosh Kumar JayaramanRank #563 · 4.3K reputationPosted Aug 7, 2012, 4:01 AM EDT
http://www.c-sharpcorner.com/UploadFile/1a81c5/export-datatable-to-excel-with-formatting-in-C-Sharp/
Abhijit baruaRank #3,722 · 397 reputationPosted Aug 7, 2012, 4:10 AM EDT
protected void ExportToPDF(object sender, EventArgs e)
{
//Get the data from database into datatable
string strQuery = "select empid, empname, city, postalcode" +
" from employee";
SqlCommand cmd = new SqlCommand(strQuery);
DataTable dt = GetData(cmd);
//Create a dummy GridView
GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = dt;
GridView1.DataBind();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition",
"attachment;filename=abc.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
}
Timothy Foster4 reputationPosted Feb 25, 2013, 10:21 PM EST
If you create a commercial product you may want to use a 3rd party component to spead up your work. For example take a look at this C# Excel Writer. This code shows how to export datatable to a new excel worksheet and save result file to disk:
DataTable dt = new DataTable();
ExcelWorkbook wb = new ExcelWorkbook();
wb.Worksheets.Add("sh1");
wb.Worksheets[0].ReadFromDataTable(dt);
wb.WriteXLS(@"c:\output.xls");