将数据从数据库导出到Excel文件

时间:2019-09-16 10:42:05

标签: sql-server asp.net-mvc

我有用于将数据导出到excel文件的代码。当我导出Excel文件时,Excel文件在打开时出错。

this is error

  

“ 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();
    }

1 个答案:

答案 0 :(得分:0)

  

您正在收到警告消息,仅因为生成了文件   不是真正的xls文件...在您的代码示例中...仅GridView RenderContol   Genrate的HTML表。

有关解决方案...,您可以使用ClosedXML Library ..和3rd Party Reference Tools ..

或者您可以引用此链接

https://www.aspsnippets.com/Articles/Solution-ASPNet-GridView-Export-to-Excel-The-file-you-are-trying-to-open-is-in-a-different-format-than-specified-by-the-file-extension.aspx