将网格视图导出为 xlsx 格式



我在将网格视图内容导出到 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";

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

此致敬意!!!

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

如果要保存真实的XLSX文件,则必须使用Excel库,如Open XML,NPOI或EasyXLS。

最新更新