c# - 将数据集导出到 excel 2007 EPPlus

标签 c# excel epplus

我正在尝试将数据集导出到 excel 2007,我无法使用用于在内容类型中使用 mime 类型导出的普通代码,例如“Response.ContentType = “application/ms-excel”;” 如果我对 xls 使用 mime 类型,当我尝试导出时会收到警告,由于客户端,我不会出现此错误,所以我开始使用 EPPlus,但现在我遇到了预期错误,例如“ArgumentNullException 未被处理用户代码”。当我调试时,我注意到 btnExportClick 方法中的变量 ds 为空,我认为错误在哪里,但我不明白在哪里,这是完整的代码:

namespace PortalFornecedores
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                this.BindGrid();
            }
        }


        public void BindGrid()
        {
            using (DataSet ds = new DataSet())
            {
                ds.ReadXml(Server.MapPath("~/Customers.xml"));
                GridFornecedor.DataSource = ds;
                GridFornecedor.DataBind();
            }
        }




        public void btnExportClick(object sender, EventArgs e)
        {
            DataTable ds = GridFornecedor.DataSource as DataTable;
            ExportExcel(ds);


        }


        public void ExportExcel(DataTable ds)
        {

            using (ExcelPackage pck = new ExcelPackage())
            {
                //Create the worksheet
                ExcelWorksheet ws = pck.Workbook.Worksheets.Add("SearchReport");

                //Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
                ws.Cells["A1"].LoadFromDataTable(ds, true);

                //prepare the range for the column headers
                string cellRange = "A1:" + Convert.ToChar('A' + ds.Columns.Count - 1) + 1;

                //Format the header for columns
                using (ExcelRange rng = ws.Cells[cellRange])
                {
                    rng.Style.WrapText = false;
                    rng.Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;
                    rng.Style.Font.Bold = true;
                    rng.Style.Fill.PatternType = ExcelFillStyle.Solid; //Set Pattern for the background to Solid
                    rng.Style.Fill.BackgroundColor.SetColor(Color.Gray);
                    rng.Style.Font.Color.SetColor(Color.White);
                }

                //prepare the range for the rows
                string rowsCellRange = "A2:" + Convert.ToChar('A' + ds.Columns.Count - 1) + ds.Rows.Count * ds.Columns.Count;

                //Format the rows
                using (ExcelRange rng = ws.Cells[rowsCellRange])
                {
                    rng.Style.WrapText = false;
                    rng.Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;
                }

                //Read the Excel file in a byte array
                Byte[] fileBytes = pck.GetAsByteArray();

                //Clear the response
                Response.Clear();
                Response.ClearContent();
                Response.ClearHeaders();
                Response.Cookies.Clear();

                //Add the header & other information
                Response.Cache.SetCacheability(HttpCacheability.Private);
                Response.CacheControl = "private";
                Response.Charset = System.Text.UTF8Encoding.UTF8.WebName;
                Response.ContentEncoding = System.Text.UTF8Encoding.UTF8;
                Response.AppendHeader("Content-Length", fileBytes.Length.ToString());
                Response.AppendHeader("Pragma", "cache");
                Response.AppendHeader("Expires", "60");
                Response.AppendHeader("Content-Disposition",
                "attachment; " +
                "filename=\"ExcelReport.xlsx\"; " +
                "size=" + fileBytes.Length.ToString() + "; " +
                "creation-date=" + DateTime.Now.ToString("R") + "; " +
                "modification-date=" + DateTime.Now.ToString("R") + "; " +
                "read-date=" + DateTime.Now.ToString("R"));
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

                //Write it back to the client
                Response.BinaryWrite(fileBytes);
                Response.End();
            }
        }

        public override void VerifyRenderingInServerForm(Control control)
        {
            /* Confirms that an HtmlForm control is rendered for the specified ASP.NET
               server control at run time. */`enter code here`
        }
    }

最佳答案

一些事情。这实际上不是 epplus 问题,而是更一般的网络问题。

首先,您在这里将网格数据源设置为数据集:

using (DataSet ds = new DataSet())
{
    ds.ReadXml(Server.MapPath("~/Customers.xml"));
    GridFornecedor.DataSource = ds;

但稍后会在此处转换为数据表:

DataTable ds = GridFornecedor.DataSource as DataTable;

当您应该首先转换为数据集然后获取其表集合的第一个表时。

但这仍然不能解决问题,因为您有一个类级别的对象,它不会跨回传存在。您需要像这样使用 session 或 View 状态变量:

public void BindGrid()
{
    using (DataSet ds = new DataSet())
    {
        ds.ReadXml(Server.MapPath("~/Customers.xml"));
        GridFornecedor.DataSource = ds;
        GridFornecedor.DataBind();
        ViewState["GridDataSource"] = ds;
    }
}


public void btnExportClick(object sender, EventArgs e)
{
    //DataTable ds = GridFornecedor.DataSource as DataTable;
    var ds = ViewState["GridDataSource"] as DataSet;
    var dt = ds.Tables[0];
    ExportExcel(dt);
}

关于c# - 将数据集导出到 excel 2007 EPPlus,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26971367/

相关文章:

excel - 引用 Excel 公式中的最后一行

c# - 如果工作簿包含数据透视表,则在添加数据后无法保存 Excel 工作表

c# - 打开 epplus 生成的文件时出错

c# - 强制 EPPLUS 以文本形式阅读

C# A 类型不能转换为 B 类型(InvalidCastException)...上下文 hell ?

c# - 如何在加载时注册 Javascript

c# - C# 属性的循环引用

c# - 如何从 DirectoryEntry 和 DN 检索 DirectoryEntry

excel - 计算列中的时间差并将其保存为具有多个电子表格的许多 excel 文件,PYTHON

excel - 如何使用 VBA 将以 = 开头的字符串插入到单元格值中?