繁体   English   中英

以.xlsx格式将GridView导出到Excel时出错

[英]Getting Error while Exporting GridView To Excel in .xlsx format

我想将GridView导出为ex​​cel(.xlsx格式)。 这是我的代码

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
 GridView gv;

protected void Button1_Click(object sender, EventArgs e)
{
    setGridView();
    Response.Clear();
    Response.ClearContent();
    Response.ClearHeaders();
    string fileName = "TestExcelFile.xlsx";
    Response.Buffer = true;
    Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    //Response.ContentType = "application/vnd.ms-excel"; // Works perfectly for .xls files
    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);
    gv.RenderControl(htw);
    Response.Write(sw.ToString());
    Response.Flush();
    Response.End();
}

private void setGridView()
{
    gv = new GridView();
    Queue q = new Queue();
    for (int i = 0; i < 20; i++)
    {
        q.Enqueue(i);
    }
    gv.DataSource = q;
    gv.DataBind();
 }
}

如果我将响应内容类型保留为: Response.ContentType = "application/vnd.ms-excel"; 那么它完美适用于excel的.xls格式。

Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; excel文件采用.xlsx格式,内容类型应为: Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

我可以使用.xls格式,但是问题是.xls格式只能容纳64000条记录,根据我的项目要求,我将获得近100000(100K)行。 因此,我必须将其导出为.xlsx格式的excel,以保存64000以上的记录。

这是错误的文本和图像: “ Excel无法打开文件'TestExcelFile [2] .xlsx',因为该文件扩展名的文件格式无效。请验证该文件未损坏并且该文件扩展名与该格式匹配文件。” 打开导出的Excel文件时出错

首先,我不知道“ Lakh”是什么,但是我想它超过65535,但是据我所知,ASP.NET Gridview无法将其直接输出为XLSX格式,因为它以原始HTML格式输出。

我建议您看一下EPPlus( http://epplus.codeplex.com/ )之类的组件,它可以更加灵活和可扩展地满足您的需求。

作为解决方法,您可以做的是,尽管这不是那么优雅,但是可以尝试以下代码:

protected void btnExportData_Click(object sender, EventArgs e)
{
    Response.Clear();

    Response.AddHeader("content-disposition", "attachment;filename=output.xlsx");
    Response.Charset = "";
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

    System.IO.StringWriter sw = new System.IO.StringWriter();
    System.Web.UI.HtmlTextWriter htmlWriter = new HtmlTextWriter(sw);

    foreach (GridViewRow row in gvData.Rows)
    {
        if (row.RowType == DataControlRowType.DataRow)
            for (int idxColumn = 0; idxColumn < row.Cells.Count; idxColumn++)
                row.Cells[idxColumn].Attributes.Add("class", "xlText");
    }

    gvData.RenderControl(htmlWriter);

    string appendStyle = @"<style> .xlText { mso-number-format:\@; } </style> ";
    Response.Write(appendStyle);

    Response.Write(sw.ToString());
    Response.End();
}

我已经在Excel 2007中使用过“ Before”,但是它是一个hack,不是很优雅。

为此的另一种解决方案(当比较相对工作量时,只会说服您获得EPPlus ,就像JaggenSWE在我前面提到的那样),它使用的是Microsoft.Office.Interop.Excel工具...

using Microsoft.Office.Interop.Excel

string path = @"C:\testoutput\output.xlsx";

Microsoft.Office.Interop.Excel.Application oXL;
Microsoft.Office.Interop.Excel.Workbook oBook;
Microsoft.Office.Interop.Excel.Worksheet oSheet;
Microsoft.Office.Interop.Excel.Range oRng;

oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = false; //This can be fun to leave enabled though :)
oXL.UserControl = false;

oBook = oXL.Workbooks.Add();
oSheet = oBook.ActiveSheet;

//This part can take a while, so throwing it into an async method elsewhere may be a thought
for (int x = 0; x < gv.Rows.Count; x++)
{
    for (int y = 0; y < gv.Columns.Count; y++)
    {
        oSheet.Cells[x + 2, y + 1] = gv.Rows[x].Cells[y].ToString();
    }
}
oBook.SaveAs(path, Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook);

oBook.Close(); //Don't forget this because the program will not close it automatically!!!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM