Click here to Skip to main content
15,892,575 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
After Exporting the Data from Datatable to Excel sheet shows this Error while Opening.

The file format and extension of '.xls' don't match.The file could be corrupted or unsafe

Below is the code used to Export to Excel

Datatable dt=BindData();
GridView GridView1=new GridView();

if (dt.Rows.Count > 0)
{
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Requisition.xls"));
Response.ContentType = "application/ms-excel";
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);

GridView1.AllowPaging = false;
GridView1.DataSource = dt;
GridView1.DataBind();

//Change the Header Row back to white color
GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
//Applying stlye to gridview header cells
for (int i = 0; i < GridView1.HeaderRow.Cells.Count; i++)
{
GridView1.HeaderRow.Cells[i].Style.Add("background-color", "#507CD1");
}

int j = 1;
//This loop is used to apply stlye to cells based on particular row
foreach (GridViewRow gvrow in GridView1.Rows)
{
gvrow.BackColor =System.Drawing.Color.White;
if (j <= GridView1.Rows.Count)
{
if (j % 2 != 0)
{
for (int k = 0; k < gvrow.Cells.Count; k++)
{
gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
}
}
}
j++;
}

GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();

}
Posted

1 solution

Your code isn't creating an Excel file. That code is only good for writing to a client that has Excel installed and it will show the data in Excel rather than the browser. It's just "smoke and mirrors" though, you aren't creating a properly formatted Excel file, to do that you'll need to use a library that supports this such as Open XML SDK, Aspose, the Excel ODBC drivers and there are no doubt others.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900