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)
{ }
}
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)
{ }
}