简体   繁体   English

将DataSet导出为ex​​cel 2007 EPPlus

[英]Export DataSet to excel 2007 EPPlus

I'm trying to export a DataSet to excel 2007,i cant use the normal code that is used to export using mime types in the contenttype like this "Response.ContentType = "application/ms-excel";" 我正在尝试将DataSet导出到excel 2007,我不能使用用于在contenttype中使用mime类型导出的普通代码,例如“Response.ContentType =”application / ms-excel“;” If i use mime type for xls i get a warning when ai try to export,i can't have this error because of the clients,so i started using EPPlus,but now i'm having expections erros,like "ArgumentNullException was unhandled by user code".When i'm debbuging i noticed that the variable ds in the btnExportClick method is null,i think that where the erros is,but i cant understand where,here is the full code: 如果我使用mime类型的xls我会在ai尝试导出时收到警告,因为客户端我不能有这个错误,所以我开始使用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`
        }
    }

Couple things. 几件事。 This isnt really an epplus problem, more general web. 这不是一个epplus问题,更一般的网络。

First, you are setting the grids DataSource to a dataSET here: 首先,您在此处将网格DataSource设置为dataSET:

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

but are later casting to a dataTABLE here: 但后来在这里转换为dataTABLE:

DataTable ds = GridFornecedor.DataSource as DataTable;

when you should first cast to a dataset then get the first table of its Table collection. 当您首先应该转换为数据集时,然后获取其Table集合的第一个表。

But that still will not fix the problem because you have a class-level object which will not presist across postbacks. 但是,这仍然无法解决问题,因为你有一个类级别的对象,它不会在回发中保持不变。 You need to use a session or viewstate variable like this: 您需要使用会话或viewstate变量,如下所示:

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);
}

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

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