简体   繁体   English

将大数据导出到ASP.Net C#中的excel

[英]Export large data to excel in ASP.Net C#

I am trying to exporting one data set to excel file. 我正在尝试将一个数据集导出到Excel文件。 the data set contains more than 20 data table (Each table will appear as the separate sheet in final output excel file) and each table contains more than 30+k rows, around 10 columns. 数据集包含20多个数据表(每个表将在最终输出excel文件中显示为单独的工作表),每个表包含30 + k行,约10列。 I am reading this data from other resource and holding it into the dataset. 我正在从其他资源读取此数据并将其保存到数据集中。 not using any database to store it. 不使用任何数据库来存储它。 I am using Open XML and Closed XML from here to do the process. 我从这里开始使用Open XML和Closed XML来完成该过程。 its working fine up to 15-20 data table, but more than 25 its taking too much time. 它最多可以处理15-20个数据表,而超过25个则花费太多时间。 Any suggestions or help will be highly appreciated for this. 任何建议或帮助,将不胜感激。

Sample code: 样例代码:

 using (XLWorkbook wb = new XLWorkbook())
 {
   foreach (DataTable dt in dsData.Tables)
   {
     wb.Worksheets.Add(dt);
   }
   Response.Clear();
   Response.Buffer = true;
   Response.Charset = "";
   Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
   Response.AddHeader("content-disposition", "attachment;filename=DataSet.xlsx");
   wb.SaveAs(Response.OutputStream);
   Response.Flush();
   Response.End();   
 }

After some research I came up a solution for this, I tested below code with 1 million + data and its woking fine. 经过一番研究后,我想出了一个解决方案,我在下面的代码中测试了100万以上的数据及其正常工作。 May be it will be helpful for some one else. 可能会对其他人有所帮助。 I removed the closedxml reference and I added "Interop.Microsoft.Office.Core.dll" refernce. 我删除了closedxml引用,并添加了“ Interop.Microsoft.Office.Core.dll”引用。 then I wrote the following code. 然后我写了下面的代码。

Required Namespace: using Excel = Microsoft.Office.Interop.Excel, using System.Runtime.InteropServices 所需的命名空间:使用Excel = Microsoft.Office.Interop.Excel,使用System.Runtime.InteropServices

    Excel.Workbook xlWorkBook;
    Excel.Application xlApp;
    Excel.Worksheet xlWorkSheet;
    Excel.Range Startrange;
    Excel.Range HeaderStartrange;
    public bool StartExport(DataTable dtbl, bool isFirst, bool isLast, string strOutputPath, string TemplateLocation, string TemplateFullName, int SectionOrder, int totalNoOfSheets)
    {
        bool isSuccess = false;
        try
        {
            if (isFirst)
            {
                CopyTemplate(TemplateLocation, strOutputPath, TemplateFullName);
                xlApp = new Excel.Application();
                if (xlApp == null)
                {
                    throw new Exception("Excel is not properly installed!!");
                }
                xlWorkBook = xlApp.Workbooks.Open(@strOutputPath + TemplateFullName, 0, false, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);

                // To Add Sheets Dynamically
                for (int i = 0; i <= totalNoOfSheets; i++)
                {
                    int count = xlWorkBook.Worksheets.Count;
                    Excel.Worksheet addedSheet = xlWorkBook.Worksheets.Add(Type.Missing,
                            xlWorkBook.Worksheets[count], Type.Missing, Type.Missing);
                    addedSheet.Name = "Sheet " + i.ToString();
                }
            }
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(SectionOrder);
            Startrange = xlWorkSheet.get_Range("A2");
            HeaderStartrange = xlWorkSheet.get_Range("A1");
            FillInExcel(Startrange, HeaderStartrange, dtbl);
            xlWorkSheet.Name = dtbl.TableName;
            if (isLast)
            {
                xlApp.DisplayAlerts = false;
                xlWorkBook.SaveAs(@strOutputPath + TemplateFullName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing,
                    Type.Missing, Type.Missing);
                xlWorkBook.Close(true, null, null);
                xlApp.Quit();
                Marshal.ReleaseComObject(xlWorkSheet);
                Marshal.ReleaseComObject(xlWorkBook);
                Marshal.ReleaseComObject(xlApp);
                GC.WaitForPendingFinalizers();
                GC.Collect();
                isSuccess = true;
            }
        }
        catch (Exception ex)
        {
            isSuccess = false;
            throw;
        }
        return isSuccess;
    }

    private void FillInExcel(Excel.Range startrange, Excel.Range HeaderStartRange, DataTable dtblData)
    {
        int rw = 0;
        int cl = 0;
        try
        {
            // Fill The Report Content Data Here
            rw = dtblData.Rows.Count;
            cl = dtblData.Columns.Count;
            string[,] data = new string[rw, cl];
            // Adding Columns Here
            for (var row = 1; row <= rw; row++)
            {
                for (var column = 1; column <= cl; column++)
                {
                    data[row - 1, column - 1] = dtblData.Rows[row - 1][column - 1].ToString();
                }
            }
            Excel.Range endRange = (Excel.Range)xlWorkSheet.Cells[rw + (startrange.Cells.Row - 1), cl + (startrange.Cells.Column - 1)];
            Excel.Range writeRange = xlWorkSheet.Range[startrange, endRange];
            writeRange.Value2 = data;
            writeRange.Formula = writeRange.Formula;
            data = null;
            startrange = null;
            endRange = null;
            writeRange = null;
        }

        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

I Called this startExport function in above for each loop with required parameters like(Data, Sheet first or last, output path,template name, section order and total number of sheets required) 我在上面为每个循环调用了startExport函数,每个循环具有所需的参数,例如(数据,首先或最后一张工作表,输出路径,模板名称,节顺序和所需工作表总数)

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

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