如何从数据表创建多个Excel文件,并使用dotnet zip将其作为zip文件下载到asp.net中

时间:2017-08-04 10:08:36

标签: c# asp.net excel memorystream

我正在编写一个程序,我必须通过该程序下载包含多个Excel文件的zip文件,例如a.xls,b.xls等。

我正在使用FOR循环来获取数据表中的数据。

现在我想使用此数据作为压缩文件导出Excel文件。

以下是我正在使用的代码,并尝试使用内存Stream来实现此目的:

string[] filetype = { "A", "B", "C", "D", "F", "G", "H" };

using (var db = new WOFFEntities())
{
    for (int i = 0; i < filetype.Length; i++)
    {
        string strFileType = Convert.ToString(filetype[i]);
        var str = db.EXPORTROCFILEREPORTs.Where(x => x.MONTHYEAR == monthYear && x.FILETYPE == strFileType).ToList();

        DataTable dtExcel = new DataTable();

        DataColumn dc = new DataColumn("MonthYear", typeof(String)); 
        dtExcel.Columns.Add(dc);
        dc = new DataColumn("FileType", typeof(String)); 
        dtExcel.Columns.Add(dc);

        dc = new DataColumn("Accoount Number", typeof(String)); 
        dtExcel.Columns.Add(dc);

        dc = new DataColumn("Invoice Number", typeof(String)); 
        dtExcel.Columns.Add(dc);

        dc = new DataColumn("Account Balance", typeof(String)); 
        dtExcel.Columns.Add(dc);

        dc = new DataColumn("No Contribution", typeof(String)); 
        dtExcel.Columns.Add(dc);

        dc = new DataColumn("Date of Invoice", typeof(String)); 
        dtExcel.Columns.Add(dc);

        dc = new DataColumn("IVAT Invoice Amount", typeof(String)); 
        dtExcel.Columns.Add(dc);

        dc = new DataColumn("Invoice Amount", typeof(String)); 
        dtExcel.Columns.Add(dc);

        dc = new DataColumn("VAT", typeof(String)); dtExcel.Columns.Add(dc);
        dc = new DataColumn("Client Name", typeof(String)); 
        dtExcel.Columns.Add(dc);

        for (int j = 0; j < str.Count; j++)
        {
            DataRow dr = dtExcel.NewRow();
            AddRowsToExcelTable(dr, j, str);
            dtExcel.Rows.Add(dr);
        }

        gvFiles.DataSource = dtExcel;
        gvFiles.DataBind();

        try
        {
            pnl.Visible = true;
            System.IO.StringWriter sw = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);

            pnl.RenderControl(htw);

            using (MemoryStream memoryStream = new MemoryStream())
            {
                HtmlTextWriter writer = .GetInstance(, memoryStream);
                pdfDoc1.Open();

                htmlparser.Parse(sr);
                pdfDoc1.Close();

                byte[] bytes = memoryStream.ToArray();
                memoryStream.Close();

                File.WriteAllBytes(folderPath + "\\" + fileName + "_" + DateTime.Now + ".pdf", bytes);
            }
        }

        Response.ClearContent();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", string.Format("attachment; 

        filename={0}", "VDF_'" + monthYear + strFileType + "'.xls"));
        Response.ContentType = "application/ms-excel";

请帮助我。

谢谢。

0 个答案:

没有答案