Wednesday, June 30, 2010

Create Excel file with save Dialog in ASP.Net

DataTable will have the data to write into Excel file
fileName will be Excel file name with extension(.xls/.xlsx)

public void SaveExcelFile(string fileName, DataTable dtData)
{
try
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline; filename=" + fileName + "");
HttpContext.Current.Response.Flush();
for (int colCount = 0; colCount < dtData.Columns.Count; colCount++)
{
HttpContext.Current.Response.Write(dtData.Columns[colCount].ColumnName.ToString());
HttpContext.Current.Response.Write("\t");
}
for (int rowCount = 0; rowCount < dtData.Rows.Count; rowCount++)
{
HttpContext.Current.Response.Write("\n");
for (int colCount = 0; colCount < dtData.Columns.Count; colCount++)
{
HttpContext.Current.Response.Write(dtData.Rows[rowCount][colCount].ToString());
HttpContext.Current.Response.Write("\t");
}

}
HttpContext.Current.Response.End();
}
catch (Exception ex)
{ }
}

3 comments:

  1. This code really work for me but, if we have ItemDataBound event then this code will definantly fail.

    ReplyDelete
  2. Dear Anuj,

    I am using asp.net with vb.net for coding. Please help me out

    Regards,
    Mohinder

    ReplyDelete
    Replies
    1. Dear Mohinder,

      do you want same code to be converted into vb.Net so that you can embed the same in your ASP.net application.

      Regards,
      Anuj Sharma

      Delete

Put your comments here

Motivational qoutes

पूरे विश्वास के साथ अपने सपनों की तरफ बढ़ें। वही ज़िन्दगी जियें जिसकी कल्पना आपने की है।