简体   繁体   English

在C#中为大型数据创建Excel

[英]Creating excel for large data in C#

I am trying to generate excel sheet for a large data about a million records. 我正在尝试为大约一百万条记录的大数据生成Excel工作表。 But when using the below code I am getting nothing. 但是当使用下面的代码时,我什么也没得到。 The code hangs up after line : wb.SaveAs(MyMemoryStream); 该代码在以下行挂起: wb.SaveAs(MyMemoryStream); . I am using closed XML for the purpose. 我为此使用封闭的XML。 Can you please guide what can be done to save large data as excel. 您能指导将Excel保存为大数据吗?

My Code: 我的代码:

private void DownloadExcel()
    {
        String Attachment = "attachment; filename=TestFile.xlsx";
        Response.ClearContent();
        DataTable dt = ds.Tables[0];


        using (XLWorkbook wb = new XLWorkbook())

        {
            wb.Worksheets.Add(dt, "Data");
            wb.Style.Font.FontName = "Courier New";
            // wb.Cell("A1:A+" + colCount + "").Style.Font.Bold = true;
            Response.Clear();
            Response.Buffer = true;
            Response.Charset = "";
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.AddHeader("content-disposition", Attachment);
            using (MemoryStream MyMemoryStream = new MemoryStream())
            {
                wb.SaveAs(MyMemoryStream);
                MyMemoryStream.WriteTo(Response.OutputStream);
                Response.Flush();
                Response.SuppressContent = true;  // Gets or sets a value indicating whether to send HTTP content to the client.
                HttpContext.Current.ApplicationInstance.CompleteRequest();
            }
        }
    }

I am ok with any other library as well to save the data as XML. 我也同意将任何其他库保存为XML。

You can try any of below approaches: 您可以尝试以下任何一种方法:

Approach 1: First you need to create the template of the excel and then use the below function. 方法1:首先,您需要创建excel模板,然后使用以下功能。 It will create new excel using your template and inserts data into excel using ACE.OLEDB. 它将使用您的模板创建新的Excel,并使用ACE.OLEDB将数据插入excel。 It will be much faster but you don't have control over formatting. 这样会更快,但是您无法控制格式。

   public static void CopyDataTableToExcel(DataTable dtExcel, String excelOutputTemplate, string outExcelPath)
    {
        File.Copy(excelOutputTemplate, outExcelPath, true);

        string qryFieldName = "";
        string qryFieldForCreate = "";
        string qryFieldValue = "";
        string qryFieldValueTemp = "";
        string qryInsert = "";

        for (int i = 0; i < dtExcel.Columns.Count; i++)
        {
            qryFieldName = qryFieldName + (qryFieldName.Trim() != "" ? ", " : "") + "[" + dtExcel.Columns[i].ColumnName + "]";
            qryFieldForCreate = qryFieldForCreate + (qryFieldForCreate.Trim() != "" ? ", " : "") +
                 "[" + dtExcel.Columns[i].ColumnName + "] varchar(255)";
        }

        // Establish a connection to the data source.
        System.Data.OleDb.OleDbConnection objConn = new System.Data.OleDb.OleDbConnection(
            "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + outExcelPath + "';Extended Properties=\"Excel 12.0;HDR=YES;\"");
        objConn.Open();

        // Add two records to the table named 'MyTable'.
        System.Data.OleDb.OleDbCommand objCmd = new System.Data.OleDb.OleDbCommand();
        objCmd.Connection = objConn;

        qryInsert = "Create table InventorySheet (" + qryFieldForCreate + ")";
        objCmd.CommandText = qryInsert;
        objCmd.ExecuteNonQuery();

        for (int i = 0; i < dtExcel.Rows.Count; i++)
        {
            qryFieldValue = "";
            for (int j = 0; j < dtExcel.Columns.Count; j++)
            {
                qryFieldValueTemp = dtExcel.Rows[i][j].ToString();
                if (qryFieldValueTemp.Length > 255)
                {
                    qryFieldValueTemp = qryFieldValueTemp.Substring(qryFieldValueTemp.Length - 255);
                }
                qryFieldValue = qryFieldValue + (qryFieldValue.Trim() != "" ? ", '" : "'") + qryFieldValueTemp.Replace("'", "''") + "'";
            }

            //qryInsert = "Insert into [Sheet1$] Values (" + qryFieldValue + ")";
            qryInsert = "Insert into InventorySheet (" + qryFieldName + ") Values (" + qryFieldValue + ")";
            objCmd.CommandText = qryInsert;
            objCmd.ExecuteNonQuery();
        }

        // Close the connection.
        objConn.Close();
        MessageBox.Show("Exported successfully.");
    }

Approach 2: Serialize the data table into xml: 方法2:将数据表序列化为xml:

DataTable dtJobMetaData = yourDataSet.Tables["PDF"];
dtJobMetaData.WriteXml(xmlPath);

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

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