使用Open Xml SDK在C#中将DataTable导出到Excel

46

我的程序可以将一些数据和DataTable导出到Excel文件(模板)中,我在模板中插入了数据到一些占位符中。这很好用,但是我也需要插入一个DataTable...

我的示例代码:

using (Stream OutStream = new MemoryStream())
{
    // read teamplate
    using (var fileStream = File.OpenRead(templatePath))
        fileStream.CopyTo(OutStream);

    // exporting
    Exporting(OutStream);
         
    // to start
    OutStream.Seek(0L, SeekOrigin.Begin);
            
    // out
    using (var resultFile = File.Create(resultPath))
        OutStream.CopyTo(resultFile);

导出的下一步方法

private void Exporting(Stream template)
{
    using (var workbook = SpreadsheetDocument.Open(template, true, new OpenSettings                          { AutoSave = true }))
    {
        // Replace shared strings
        SharedStringTablePart sharedStringsPart = workbook.WorkbookPart.SharedStringTablePart;
        IEnumerable<Text> sharedStringTextElements = sharedStringsPart.SharedStringTable.Descendants<Text>();
           
        DoReplace(sharedStringTextElements);
        // Replace inline strings
        IEnumerable<WorksheetPart> worksheetParts = workbook.GetPartsOfType<WorksheetPart>();
          
        foreach (var worksheet in worksheetParts)
        {
            DoReplace(worksheet.Worksheet.Descendants<Text>());
        }

        int z = 40;
        foreach (System.Data.DataRow row in ExcelWorkXLSX.ToOut.Rows)
        {
            for (int i = 0; i < row.ItemArray.Count(); i++)
            { 
                ExcelWorkXLSX.InsertText(workbook, row.ItemArray.ElementAt(i).ToString(), getColumnName(i), Convert.ToUInt32(z)); }
                z++;
            }
        } 
        
    }
}

但是这个代码片段输出 DataTable 的速度非常慢......

我怎样才能快速且准确地将 DataTable 导出到 Excel?


你需要使用Open XML SDK吗? - KLIM8D
嗯... 不过可以使用Open XML SDK快速读写Excel文件。在我的程序中,我读取xlsx文件,将数据抓取到DataGridView(使用DataTable),重新检查数据。最初我使用Interop,但它需要Excel并且非常慢。我的问题仅在于导出。但是,此时我不想重写太多代码 :) - user1576474
8个回答

96

我写了这个快速示例,对我来说它运行良好。 我只使用了一个数据集和一个表进行了测试,但我想这可能已经足够了。

请注意,我将所有单元格都视为字符串(甚至不是共享字符串)。 如果您想使用共享字符串,您可能需要微调我的示例。

编辑:为使此功能正常工作,必须将WindowsBase和DocumentFormat.OpenXml引用添加到项目中。

享受吧,

private void ExportDataSet(DataSet ds, string destination)
        {
            using (var workbook = SpreadsheetDocument.Create(destination, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
            {
                var workbookPart = workbook.AddWorkbookPart();

                workbook.WorkbookPart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();

                workbook.WorkbookPart.Workbook.Sheets = new DocumentFormat.OpenXml.Spreadsheet.Sheets();

                foreach (System.Data.DataTable table in ds.Tables) {

                    var sheetPart = workbook.WorkbookPart.AddNewPart<WorksheetPart>();
                    var sheetData = new DocumentFormat.OpenXml.Spreadsheet.SheetData();
                    sheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet(sheetData);

                    DocumentFormat.OpenXml.Spreadsheet.Sheets sheets = workbook.WorkbookPart.Workbook.GetFirstChild<DocumentFormat.OpenXml.Spreadsheet.Sheets>();
                    string relationshipId = workbook.WorkbookPart.GetIdOfPart(sheetPart);

                    uint sheetId = 1;
                    if (sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Count() > 0)
                    {
                        sheetId =
                            sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Select(s => s.SheetId.Value).Max() + 1;
                    }

                    DocumentFormat.OpenXml.Spreadsheet.Sheet sheet = new DocumentFormat.OpenXml.Spreadsheet.Sheet() { Id = relationshipId, SheetId = sheetId, Name = table.TableName };
                    sheets.Append(sheet);

                    DocumentFormat.OpenXml.Spreadsheet.Row headerRow = new DocumentFormat.OpenXml.Spreadsheet.Row();

                    List<String> columns = new List<string>();
                    foreach (System.Data.DataColumn column in table.Columns) {
                        columns.Add(column.ColumnName);

                        DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
                        cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
                        cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(column.ColumnName);
                        headerRow.AppendChild(cell);
                    }


                    sheetData.AppendChild(headerRow);

                    foreach (System.Data.DataRow dsrow in table.Rows)
                    {
                        DocumentFormat.OpenXml.Spreadsheet.Row newRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
                        foreach (String col in columns)
                        {
                            DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
                            cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
                            cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(dsrow[col].ToString()); //
                            newRow.AppendChild(cell);
                        }

                        sheetData.AppendChild(newRow);
                    }

                }
            }
        }

5
我认为workbook.WorkbookPart.Workbook = new...workbook.WorkbookPart.Workbook.Sheets = new应该移至foreach循环之外。否则,循环的每个迭代都会替换工作表,导致Excel文件只包含最终的DataTable - Brian
2
是的,看起来很好。顺便说一下,调用.Max(s=>s.SheetId.Value)比调用.Select(s=>s.SheetId.Value).Max()更简洁。同样地,您不需要一个List<String> columns,因为DataRow有一个DataColumn索引器;第二个foreach也可以遍历table.Columns - Brian
我在 DocumentFormat.OpenXml 参考文档中找不到 SpreadsheetDocumentWorksheetPart 的引用。您能指定这些引用吗? - AaA
1
我自己解决了。为了使这个工作,需要将 WindowsBaseDocumentFormat.OpenXml 引用添加到项目中。此外,SpreadsheetDocumentWorksheetPartDocumentFormat.OpenXml.Packaging 命名空间中。 - AaA
哈哈,这是我的荣幸。很高兴能帮到你! - undefined
显示剩余6条评论

18

eburgos,我稍微修改了您的代码,因为当您的数据集中有多个数据表时,它只是在电子表格中覆盖它们,所以您只剩下一个工作簿。我基本上只是把创建工作簿的部分移到了循环外面。这是更新后的代码。

private void ExportDSToExcel(DataSet ds, string destination)
{
    using (var workbook = SpreadsheetDocument.Create(destination, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
    {
        var workbookPart = workbook.AddWorkbookPart();
        workbook.WorkbookPart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();
        workbook.WorkbookPart.Workbook.Sheets = new DocumentFormat.OpenXml.Spreadsheet.Sheets();

        uint sheetId = 1;

        foreach (DataTable table in ds.Tables)
        {
            var sheetPart = workbook.WorkbookPart.AddNewPart<WorksheetPart>();
            var sheetData = new DocumentFormat.OpenXml.Spreadsheet.SheetData();
            sheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet(sheetData);                

            DocumentFormat.OpenXml.Spreadsheet.Sheets sheets = workbook.WorkbookPart.Workbook.GetFirstChild<DocumentFormat.OpenXml.Spreadsheet.Sheets>();
            string relationshipId = workbook.WorkbookPart.GetIdOfPart(sheetPart);

            if (sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Count() > 0)
            {
                sheetId =
                    sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Select(s => s.SheetId.Value).Max() + 1;
            }

            DocumentFormat.OpenXml.Spreadsheet.Sheet sheet = new DocumentFormat.OpenXml.Spreadsheet.Sheet() { Id = relationshipId, SheetId = sheetId, Name = table.TableName };
            sheets.Append(sheet);

            DocumentFormat.OpenXml.Spreadsheet.Row headerRow = new DocumentFormat.OpenXml.Spreadsheet.Row();

            List<String> columns = new List<string>();
            foreach (DataColumn column in table.Columns)
            {
                columns.Add(column.ColumnName);

                DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
                cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
                cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(column.ColumnName);
                headerRow.AppendChild(cell);
            }

            sheetData.AppendChild(headerRow);

            foreach (DataRow dsrow in table.Rows)
            {
                DocumentFormat.OpenXml.Spreadsheet.Row newRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
                foreach (String col in columns)
                {
                    DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
                    cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
                    cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(dsrow[col].ToString()); //
                    newRow.AppendChild(cell);
                }

                sheetData.AppendChild(newRow);
            }
        }
    }
}

谢谢,我刚刚看到了布莱恩的评论,然后我也在我的上面做了同样的事情。 - eburgos
可以包括一个返回字节的版本,以及一个只接受DataTable而不是DataSet的版本。 - Seabizkit

9
我还编写了一个C#/VB.Net的“导出到Excel”库,它使用OpenXML和(更重要的是)OpenXmlWriter,因此在编写大文件时不会耗尽内存。
可以在此处下载完整的源代码和演示: Export to Excel 使用起来非常简单。只需将要写入的文件名以及DataTableDataSetList<>传递给它即可。
CreateExcelFile.CreateExcelDocument(myDataSet, "MyFilename.xlsx");

如果你从ASP.Net应用程序中调用它,将HttpResponse传递给它以将文件写出。

CreateExcelFile.CreateExcelDocument(myDataSet, "MyFilename.xlsx", Response);

2
抱歉...!现在它又活过来了。 - Mike Gledhill
@MikeGledhill 有没有异步处理的解决方法?当我尝试写入一个巨大的文件时,会出现内存不足异常,我已经阅读了所有相关的帖子,似乎这是受可用内存限制的问题。 - afr0
@Afr0:这不应该是这种情况。我的库使用OpenXmlWriter,它会在进行操作时立即将数据写出,而不是首先尝试在内存中构建整个Excel文件。如果可能的话,请通过我的网站给我发送电子邮件,我会看看能否提供帮助。 - Mike Gledhill
也许我得到的代码库写法有些问题,不太确定。 - afr0
2
导出链接失效。 - jbrekke
显示剩余2条评论

1

我编写了自己的Excel导出程序,因为其他程序无法完全满足我的需求。它速度快,并允许对单元格进行大量格式设置。您可以在以下链接中查看:


https://openxmlexporttoexcel.codeplex.com/

我希望它能够帮到你。


该网站无法访问。 - federico

0
你可以在这里查看我的库here。在文档部分,您将找到如何导入数据表格的说明。
你只需要写:
using (var doc = new SpreadsheetDocument(@"C:\OpenXmlPackaging.xlsx")) {
    Worksheet sheet1 = doc.Worksheets.Add("My Sheet");
    sheet1.ImportDataTable(ds.Tables[0], "A1", true);
}

希望能对你有所帮助!


0
我尝试了接受的答案,但在尝试打开生成的 Excel 文件时收到了文件已损坏的消息。我通过对代码进行一些修改(例如添加以下行到代码结尾)来解决这个问题。

workbookPart.Workbook.Save();

我已经在这个链接上发布了完整的代码,用C#实现将DataTable导出到Excel。


0
你可以尝试看看这个库。我在我的一个项目中使用过它,发现它非常易于使用、可靠且快速(我只用它来导出数据)。

http://epplus.codeplex.com/


谢谢!这是一个好主意!我会尝试它只为出口。 - user1576474

0
我想添加这个答案,因为我使用了这个问题的主要答案作为基础,使用OpenXML从datatable导出到Excel,但当我发现它比上述方法快得多时,就转向了OpenXMLWriter。
您可以在下面的链接中找到我的完整答案细节。我的代码是用VB.NET编写的,所以您需要进行转换。 如何将DataTable导出到Excel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接