将DataSet导出为ex​​cel 2007 EPPlus

时间:2014-11-17 11:09:53

标签: c# excel epplus

我试图将DataSet导出到excel 2007,我无法使用用于在内容类型中使用mime类型导出的常规代码,例如" Response.ContentType =" application / MS-Excel的&#34 ;;" 如果我使用mime类型的xls我在ai尝试导出时会收到警告,因为客户端我不会有这个错误,所以我开始使用EPPlus,但现在我有了错误的错误,比如& #34; ArgumentNullException未被用户代码处理"。当我正在进行debbuging时,我发现btnExportClick方法中的变量ds为null,我认为错误在哪里,但是我不知道在哪里,这里是完整代码:

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`
        }
    }

1 个答案:

答案 0 :(得分:2)

夫妻俩。这不是一个epplus问题,更普遍的网络。

首先,您在此处将网格DataSource设置为dataSET:

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

但稍后在这里转换为dataTABLE:

DataTable ds = GridFornecedor.DataSource as DataTable;

当您首次投射到数据集时,然后获取其Table集合的第一个表。

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

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