【问题标题】:Export Gridview to xlsx format将 Gridview 导出为 xlsx 格式
【发布时间】:2017-10-22 16:40:23
【问题描述】:

我在将 gridview 内容导出到 excel 文件(xlsx 扩展名)时遇到问题。 我可以像 xls 扩展一样导出它,但不能像 xlsx 一样导出。 我的代码是:

#region === EXPORT GRID A EXCEL ===

protected void imgBtn_Consol_Export_Click(object sender, ImageClickEventArgs e)
{
    Response.Clear();
    Response.AddHeader("content-disposition", "attachment;filename=Lotes.xls");

    Response.Charset = "";
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.ContentType = "application/vnd.xlsx";


    System.IO.StringWriter stringWrite = new System.IO.StringWriter();
    System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
    gvwLotConsol_Plant.RenderControl(htmlWrite);

    //style to format numbers to string
    string style = @"<style> TD { mso-number-format:\@; } </style>"; //para formato texto
    Response.Write(style);

    Response.Write(stringWrite.ToString());
    Response.End();

}

public override void VerifyRenderingInServerForm(System.Web.UI.Control control)
{/* Verifies that the control is rendered */}

#endregion

我尝试使用 xls 扩展但不起作用,我尝试使用:

Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

它不起作用,如果有人可以帮助我,那就太好了。

最好的问候!!!

【问题讨论】:

  • “不起作用”不是对您的问题的有用描述。自从在 Office 应用程序中引入“扩展强化”以来,将数据导出为 HTML 并发送 Excel 标头一直是一个问题。基本上,如果您将内容标记为 Excel 格式,则它实际上需要 为 Excel 格式。

标签: asp.net excel gridview


【解决方案1】:

您的代码不以 xls 或 xlsx 文件格式保存。它保存一个带有 xls 或 xlsx 扩展名的 html 文件。 HTML 是一种文本文件格式,而 Excel 文件格式是二进制格式。打开 HTML 文件时,MS Excel 会识别出不一致并发出警告。

如果您想保存真正的 XLSX 文件,您必须使用 Excel 库,例如 Open XMLNPOIEasyXLS

【讨论】:

    猜你喜欢
    • 2014-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多