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

时间:2018-11-14 11:48:31

标签: c# excel closedxml

我正在尝试为大约一百万条记录的大数据生成Excel工作表。但是当使用下面的代码时,我什么也没得到。代码在第wb.SaveAs(MyMemoryStream);行之后挂断。我为此使用封闭的XML。您能指导将Excel保存为大数据吗?

我的代码:

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

我也同意将任何其他库保存为XML。

1 个答案:

答案 0 :(得分:0)

您可以尝试以下任何一种方法:

方法1:首先,您需要创建excel模板,然后使用以下功能。它将使用您的模板创建新的Excel,并使用ACE.OLEDB将数据插入excel。这样会更快,但是您无法控制格式。

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

方法2::将数据表序列化为xml:

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