我正在将一个GridView导出到一个Excel文件,但是当我打开这个文件时,首先我得到一个关于格式类型和扩展名不匹配的错误,当我打开它时,整个页面被带入Excel文件,而不仅仅是网格视图。如何将GridView导出到Excel?
enter code here
protected void ExportToExcel(object sender, EventArgs e)
{
try
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
//To Export all pages
gridCustomer.AllowPaging = false;
//this.gridCustInfoBind(1);
gridCustAllInfoBind(1);
gridCustomer.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in gridCustomer.HeaderRow.Cells)
{
cell.BackColor = gridCustomer.HeaderStyle.BackColor;
}
foreach (GridViewRow row in gridCustomer.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = gridCustomer.AlternatingRowStyle.BackColor;
}
else
{
cell.BackColor = gridCustomer.RowStyle.BackColor;
}
cell.CssClass = "textmode";
}
}
gridCustomer.RenderControl(hw);
//style to format numbers to string
string style = @"<style> .textmode { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
catch (Exception ex)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('Exception Message: " + ex.Message.Replace("'", "").Replace("\"", "") + "');", true);
}
}
因为生成的文件内容的.html不.xls的 – Slai
如何将其转化为.xls的,你可以修改我的代码。 –