Ankush Chauhan

Ankush Chauhan

  • 1.5k
  • 146
  • 2.1k

how to export Datable into .xls only and download code .

Feb 1 2016 2:33 AM
i have write this code : 
ExcelPackage excel = new ExcelPackage();
var workSheet = excel.Workbook.Worksheets.Add(filnam);
//adding header column for the sheet
for (var i = 0; i < dt.Columns.Count; i++)
{
workSheet.Cells[1, i + 1].Value = dt.Columns[i].ColumnName;
}
//writing each row data
for (var j = 0; j < dt.Rows.Count; j++)
{
for (var i = 0; i < dt.Columns.Count; i++)
{
workSheet.Cells[j + 2, i + 1].Value = (dt.Rows[j][i]).ToString();
}
}
using (var memoryStream = new MemoryStream())
{
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + filnam +".xls");
excel.SaveAs(memoryStream);
memoryStream.WriteTo(HttpContext.Current.Response.OutputStream);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Close();
}
 
but  when it downloaded ,i opened it in MSOffice2007 it giving warning i.e.
"The file you are trying to open, 'filename.xls', is in a different format than specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file. Do you want to open the file now?"
please solve this . Thnks
 
 
 
 

Answers (2)