将数据集导出到 Excel 2007 EPPlus

2024-01-15

我正在尝试将数据集导出到 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;

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

但这仍然无法解决问题,因为您有一个类级别的对象,该对象不会在回发中保留。您需要使用会话或视图状态变量,如下所示:

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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将数据集导出到 Excel 2007 EPPlus 的相关文章

随机推荐

  • MatMul 运算在张量流中如何工作?

    我注意到张量流中定义的 MatMul 运算 形状函数 Status MatMulShape shape inference InferenceContext c ShapeHandle a TF RETURN IF ERROR c gt W
  • 如何更改Mongo文档中嵌套字段的数据类型?

    我的 Mongo 结构如下 topProcesses cpuUtilizationPercent 0 0 processId 1 memoryUtilizationPercent 0 1 command init user root cpu
  • Firefox 中保存的密码发送空字段

    我在保存浏览器凭据时遇到问题 我第一次使用应用程序登录时 浏览器要求我保存字段 我按 确定 但是当我第二次登录并且浏览器使用保存的凭据填写表单字段时 我按登录 浏览器发送不带参数的请求 HTML div div
  • 如何使用所有处理器在 MPI 中发送/接收

    该程序使用 C Lagrange 和 MPI 编写 我是 MPI 新手 想要使用所有处理器进行一些计算 包括进程 0 为了学习这个概念 我编写了以下简单程序 但是这个程序在接收到进程0的输入后挂在底部 并且不会将结果发送回进程0 inclu
  • 通知图标在通知托盘上为白色

    我的通知托盘上的应用程序图标在 Android 5 上变成白色 我见过这个Android 5 Lollipop 中通知栏图标变白 https stackoverflow com questions 28387602 notification
  • 如何在 Windows 窗体应用程序中创建 Alt 快捷方式?

    我想为 Windows 窗体应用程序中的某些控件创建键盘快捷键 Example 注意带下划线的 F E V P B I have a label and a textbox control I d like to associate tha
  • 可以检测页面抓取吗?

    所以我刚刚创建了一个为我执行页面抓取的应用程序 并运行它 效果很好 我想知道是否有人能够弄清楚代码正在被页面抓取 无论他们是否为此目的编写了代码 我用java编写了代码 它几乎只是检查一行html代码 我想在向该程序添加更多代码之前我应该
  • CGContextClipToMask 返回空白图像

    我是石英新手 我有 2 个图像 一个背景和一个带有剪切形状的蒙版 我想将其放置在背景上以剪切出一部分 生成的图像应该是切口的形状 这是我的面具 中间的形状是 0 alpha 这是我的代码 UIView canvas sender super
  • 稍后发送电子邮件

    我想知道是否 v1 0 me sendMail具有延迟发送电子邮件的能力 在 Outlook 客户端中 您可以指定希望在稍后的日期和时间发送电子邮件 我四处探听 看看是否有一个属性可以在消息对象上设置来指示这一点 有人找到办法让它工作吗 当
  • iOS 在 UIWebView 表单输入中使用 UIKeyboardTypeDecimalPad

    我想用 显示小数点 在基于 cordova 的应用程序中本机应用程序使用的左上角 我见过很多使用私有 API 等的线程 但我想要一个可以用于应用程序商店提交的解决方案 任何帮助表示赞赏 我已经尝试过一些东西 this https stack
  • “范围错误:超出最大调用堆栈大小”为什么?

    如果我跑 Array apply null new Array 1000000 map Math random 在 Chrome 33 上 我得到 RangeError Maximum call stack size exceeded Wh
  • 如何在两个不同的核心数据模型之间共享实体

    我想知道如何在两个不同的核心数据模型之间共享实体 例如 我有一个 Universe 模型描述了 世界数据 以其 国家数据 另一方面 我有一个 人口 模型 它描述了 人类数据 以其 国家数据 我绝对希望将我的模型分开 提前致谢 你检查过了吗核
  • 在QML中动态创建ListModel

    当我需要在运行时创建任何 QML 组件时 我可以使用该指南 http qt project org doc qt 5 qtqml javascript dynamicobjectcreation html http qt project o
  • 输入字段值中的 HTML

    如何让 HTML 在输入字段的值中起作用 如果值中包含 HTML 它将显示为纯文本 有没有办法做这样的事情
  • 在 MATLAB 中嵌入 Python

    我正在尝试将 Python 2 6 嵌入到 MATLAB 7 12 中 我想嵌入一个用 C 编写的 mex 文件 这对于使用标量的小型简单示例来说效果很好 但是 如果以任何方式导入 Numpy 1 6 1 MATLAB 都会崩溃 我说无论如
  • Spring微服务端到端测试

    我想为使用 Spring Boot 构建的管道编写端到端测试 考虑两个微服务 A B 其中 B 消耗 A 的输出并生成 RESTful API 它们使用rabbitmq连接并依赖外部数据库 我想实现类似的目标 创建一个包含两个微服务的新项目
  • 如何从 RabbitMQ 获取旧消息?

    我使用 Bunny Ruby 发布 RabbitMQ 消息 如下所示 x publish Message n to s routing key gt mychannel 并像这样订阅 ch conn create channel x ch
  • Autofac - 构建前解决

    使用 Unity 可以在构建容器之前解决依赖关系 Autofac 也可以吗 下面的代码演示了我的场景 我需要解决ICacheRepository为了 更新 单例CacheHelper 在 Unity 中 这可以简单地完成container
  • 4 个浮动 DIV 在使用 CSS 的缩小屏幕上对称响应

    1 2 3 4 我有四个向左浮动的 DIV 上图 使用简单的 CSS float left 宽度 128 像素 高度 128 像素 当我缩小屏幕时 最后一个 DIV 正确跳到下一行 1 2 3 4 但我真正想要的是最后两个块跳到下一行 以保
  • 将数据集导出到 Excel 2007 EPPlus

    我正在尝试将数据集导出到 excel 2007 我无法使用用于在内容类型中使用 mime 类型导出的正常代码 如下所示 Response ContentType application ms excel 如果我对 xls 使用 mime 类