我有用于将数据导出到excel文件的代码。当我导出Excel文件时,Excel文件在打开时出错。
“ Farmer_Sample(4).xls”的文件格式和扩展名不匹配。 该文件可能已损坏或不安全。除非您相信其来源, 不要打开它。您是否仍要打开它?
(是)(否)(帮助)
这是代码:
public ActionResult ExportToExcel()
{
var data = db.farmerSample.ToList();
GridView gridview = new GridView();
gridview.DataSource = data;
gridview.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename = Farmer_Sample.xls");
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// render the GridView to the HtmlTextWriter
gridview.RenderControl(htw);
// Output the GridView content saved into StringWriter
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
return View();
}
答案 0 :(得分:0)
您正在收到警告消息,仅因为生成了文件 不是真正的xls文件...在您的代码示例中...仅GridView RenderContol Genrate的HTML表。
有关解决方案...,您可以使用ClosedXML Library ..和3rd Party Reference Tools ..
或者您可以引用此链接