将代码移动到类会导致HttpException错误

时间:2015-12-16 12:54:58

标签: c# asp.net excel epplus

我编写的代码使用EPPlus将数据从网页导出到excel,我希望在我的项目中多次重复使用,因此我已将代码移动到自己的类中。

在页面代码中工作正常但是当我将它移动到自己的类时,我在cnts <- colSums(apply(uncs, 1, function(r) apply(dt, 1, function(r2) all(r == r2)))) cbind(comb = apply(uncs, 1, paste), n = cnts) 行上出现以下错误:

Response.Clear()

这是我的代码

ExcelHelper类

System.Web.HttpException (0x80004005): Response is not available in this context

调用类的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;
using OfficeOpenXml;
using OfficeOpenXml.Table;

namespace myClassLib
{
    public class ExcelHelper : System.Web.UI.Page
    {

        public void exportExcel(DataTable myDataTable)
        {
            Response.Clear();
            Response.Charset = "";
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.AddHeader("content-disposition", "attachment;filename=Output.xlsx");

            DataTable dt= myDataTable;

            ExcelPackage pck = new ExcelPackage();
            using(pck)
            {
                ExcelWorksheet wsDt = pck.Workbook.Worksheets.Add("Sheet1");
                wsDt.Cells["A1"].LoadFromDataTable(dt, true, TableStyles.None);

                int colNumber = 1;

                foreach (DataColumn col in dt.Columns) 
                {

                    if (col.DataType == typeof(DateTime))
                    {
                        wsDt.Column(colNumber).Style.Numberformat.Format = "yyyy-mm-dd";
                    }
                    colNumber = colNumber + 1;
                }

                wsDt.Cells[wsDt.Dimension.Address].AutoFitColumns();

                Response.BinaryWrite(pck.GetAsByteArray());
            }

            Response.Flush();
            Response.End();

        }

    }
}

非常感谢任何帮助

1 个答案:

答案 0 :(得分:0)

您从Page继承了帮助程序,可能是因为您希望访问Response属性中提供的HttpResponse实例。但是,Page类应该由ASP.NET http管道实例化,以便正确设置其所有内部状态。在您的方案中不会发生这种情况。如果您按如下方式重构它,您可以在帮助程序类中生成Excel,并将一些额外的东西也导出到文件中。

public class ExcelExporter 
{
    DataTable dt;
    string filename = "Output.xlsx";
    // create exporter for datatable
    public ExcelExporter(DataTable dt)
    {
        this.dt = dt;
    }

    // creates an exporter for a datatable and filename
    public ExcelExporter(DataTable dt, string filename):this(dt)
    {
        this.filename = filename;
    }

    // exports excel to given httpResponse
    public void Export(HttpResponse response)
    {
        Response.Clear();
        Response.Charset = "";
        Response.ContentEncoding = System.Text.Encoding.UTF8;
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.AddHeader(
            "content-disposition", 
            String.Format("attachment;filename={0}",filename));

        Response.BinaryWrite(Export());

        Response.Flush();
        Response.End();

    }

    // export excel package in path with defaukt name
    public void Export(string path)
    {
        Export(path, filename);
    }

    // export excel package as file in path
    public void Export(string path, string file)
    {
        var full = Path.Combine(path, file);
        File.WriteAllBytes(full, Export());
    }

    //exort Excel package as Byte array
    public byte[] Export()
    {
        ExcelPackage pck = new ExcelPackage();
        using (pck)
        {
            ExcelWorksheet wsDt = pck.Workbook.Worksheets.Add("Sheet1");
            wsDt.Cells["A1"].LoadFromDataTable(dt, true, TableStyles.None);

            int colNumber = 1;

            foreach (DataColumn col in dt.Columns)
            {

                if (col.DataType == typeof(DateTime))
                {
                    wsDt.Column(colNumber).Style.Numberformat.Format = "yyyy-mm-dd";
                }
                colNumber = colNumber + 1;
            }

            wsDt.Cells[wsDt.Dimension.Address].AutoFitColumns();
            return pck.GetAsByteArray();   
        }
    }

}

要使用这个新版本,您可以从ASP.NET页面中按如下方式调用它:

myExcelHelper = new ExcelExproter(myDataTable);
myExcelHelper.Export(Response); // Response will be the HttpResponse of the current executing page