OpenXML 动态创建“表/数据透视表”

Posted

技术标签:

【中文标题】OpenXML 动态创建“表/数据透视表”【英文标题】:OpenXML Create "Table/Pivot Table" Dynamically 【发布时间】:2014-10-18 20:15:36 【问题描述】:

我正在创建一个在内存上生成 excel 的示例程序。 该程序已经生成了 excel,但是我不能让表格工作......

程序:

public class Program

    static void Main(string[] args)
    
        CreateCurrentAccount();
    

    static void CreateCurrentAccount()
    
        byte[] _buffer = ExcelGenerator.CurrentAccount.GetExcel();
        File.WriteAllBytes("CurrentAccount.xlsx", _buffer);
    

ExcelGenerator 类:

public class ExcelGenerator

    static uint? _generalStyle = 0;
    static uint? _dateStyle = 1;
    static uint? _currencyStyle = 2;
    static uint? _percentageStyle = 3;
    static int maxStyleSheetName = 31;

    public static class CurrentAccount
    
        static uint? _headerStyle = 4;
        static uint? _tableHeaderStyle = 5;
        static uint? _totalHeaderStyle = 6;

        public static byte[] GetExcel()
        
            using (MemoryStream ms = new MemoryStream())
            
                SpreadsheetDocument spreadsheet;
                Worksheet worksheet;

                spreadsheet = OpenXML.CreateWorkbook(ms);

                // styles
                OpenXML.AddBasicStyles(spreadsheet);
                AddAdvancedStyles(spreadsheet);

                string styleSheetName = ("Conta Corrente" /* + customer.Name*/);
                OpenXML.AddWorksheet(spreadsheet, styleSheetName.Length > maxStyleSheetName ? styleSheetName.Substring(0, maxStyleSheetName) : styleSheetName);
                worksheet = spreadsheet.WorkbookPart.WorksheetParts.First().Worksheet;

                // Sheet 1 Header
                OpenXML.MergeTwoCells(worksheet, "A1", "F1");
                OpenXML.SetCellValue(spreadsheet, worksheet, 1, 1, CellValues.String, "Conta Corrente", _headerStyle, true);

                // Header Table
                OpenXML.SetCellValue(spreadsheet, worksheet, 1, 3, CellValues.String, "Tipo de Doc.", _tableHeaderStyle, true);
                OpenXML.SetCellValue(spreadsheet, worksheet, 2, 3, CellValues.String, "Nr. Doc.", _tableHeaderStyle, true);
                OpenXML.SetCellValue(spreadsheet, worksheet, 3, 3, CellValues.String, "Valor Doc.", _tableHeaderStyle, true);
                OpenXML.SetCellValue(spreadsheet, worksheet, 4, 3, CellValues.String, "Valor Pendente", _tableHeaderStyle, true);
                OpenXML.SetCellValue(spreadsheet, worksheet, 5, 3, CellValues.String, "Data Registo", _tableHeaderStyle, true);
                OpenXML.SetCellValue(spreadsheet, worksheet, 6, 3, CellValues.String, "Data Vencimento", _tableHeaderStyle, true);

                // Table
                var currentAccountData = GetData();

                uint rowIdx = 4;
                foreach (var item in currentAccountData)
                
                    OpenXML.SetCellValue(spreadsheet, worksheet, 1, rowIdx, CellValues.String, item.TypeDoc, _generalStyle, true);
                    OpenXML.SetCellValue(spreadsheet, worksheet, 2, rowIdx, CellValues.String, item.NrDoc, _generalStyle, true);
                    if (item.DocValue != null)
                        OpenXML.SetCellValue(spreadsheet, worksheet, 3, rowIdx, Convert.ToDouble(item.DocValue), _currencyStyle, true);
                    if (item.PendingValue != null)
                        OpenXML.SetCellValue(spreadsheet, worksheet, 4, rowIdx, Convert.ToDouble(item.PendingValue), _currencyStyle, true);
                    if (item.RecordDate != null)
                        OpenXML.SetCellValue(spreadsheet, worksheet, 5, rowIdx, item.RecordDate, _dateStyle, true);
                    if (item.SalaryDate != null)
                        OpenXML.SetCellValue(spreadsheet, worksheet, 6, rowIdx, item.SalaryDate, _dateStyle, true);

                    rowIdx++;
                

                TableParts tableParts1 = new TableParts()  Count = (uint)1U ;
                TablePart tablePart1 = new TablePart()  Id = "rId1" ;
                tableParts1.Append(tablePart1);
                worksheet.Append(tableParts1);

                OpenXML.CreateTable(spreadsheet, worksheet, "table1", 3U, 1U, (uint)currentAccountData.Count + 3, 6U);
                TableDefinitionPart tableDefinitionPart1 = worksheet.WorksheetPart.TableDefinitionParts.FirstOrDefault<TableDefinitionPart>();

                // Total
                OpenXML.SetCellValue(spreadsheet, worksheet, 8, 2, CellValues.String, "Total Documento", _totalHeaderStyle, true);
                OpenXML.SetCellFormula(spreadsheet, worksheet, 9, 2, "=SUM(C4:C1048576)", 2, true);

                OpenXML.SetCellValue(spreadsheet, worksheet, 8, 3, CellValues.String, "Total Pendente", _totalHeaderStyle, true);
                OpenXML.SetCellFormula(spreadsheet, worksheet, 9, 3, "=SUM(D4:D1048576)", 2, true);

                // Last Sync
                var lastSync = DateTime.Now;
                OpenXML.SetCellValue(spreadsheet, worksheet, 8, 1, CellValues.String, "Última Sincronização", _totalHeaderStyle, true);
                OpenXML.SetCellValue(spreadsheet, worksheet, 9, 1, lastSync, _dateStyle, true);

                // Set column widths
                OpenXML.SetColumnWidth(worksheet, 1, 22);
                OpenXML.SetColumnWidth(worksheet, 2, 22);
                OpenXML.SetColumnWidth(worksheet, 3, 22);
                OpenXML.SetColumnWidth(worksheet, 4, 22);
                OpenXML.SetColumnWidth(worksheet, 5, 22);
                OpenXML.SetColumnWidth(worksheet, 6, 22);

                OpenXML.SetColumnWidth(worksheet, 8, 22);
                OpenXML.SetColumnWidth(worksheet, 9, 22);

                worksheet.Save();
                spreadsheet.Close();

                return ms.ToArray();
            
        
    

创建表方法

public static void CreateTable(SpreadsheetDocument document, Worksheet worksheet, string TableName, uint rowStart, uint columnStart, uint rowEnd, uint columnEnd)
    
        string cellAddressStart = ColumnNameFromIndex(columnStart) + rowStart;
        string cellAddressEnd = ColumnNameFromIndex(columnEnd) + rowEnd;
        string tableAddress = cellAddressStart + ":" + cellAddressEnd;

        TableDefinitionPart tableDefinitionPart1 = worksheet.WorksheetPart.AddNewPart<TableDefinitionPart>("rId1");

        Table table1 = new Table()  Id = (UInt32Value)2U, Name = TableName, DisplayName = TableName, Reference = tableAddress, TotalsRowShown = false ;
        AutoFilter autoFilter1 = new AutoFilter()  Reference = tableAddress ;

        uint cellRangeCount = columnEnd - columnStart;
        TableColumns tableColumns1 = new TableColumns()  Count = (UInt32Value)(cellRangeCount) ;
        uint cellCount = 1;
        for (uint idxColumns = columnStart; idxColumns < columnEnd; idxColumns++)
        
            CellValue cell = GetCellValue(document, worksheet, idxColumns, rowStart);
            TableColumn tableColumn1 = new TableColumn()  Id = (UInt32Value)cellCount, Name = cell.InnerText ;
            tableColumns1.Append(tableColumn1);
            cellCount++;
        

        TableStyleInfo tableStyleInfo1 = new TableStyleInfo()  Name = "TableStyleMedium2", 
                                                                ShowFirstColumn = false, 
                                                                ShowLastColumn = false, 
                                                                ShowRowStripes = true, 
                                                                ShowColumnStripes = false ;

        table1.Append(autoFilter1);
        table1.Append(tableColumns1);
        table1.Append(tableStyleInfo1);

        tableDefinitionPart1.Table = table1;
    

我正在添加单元格(行)

var currentAccountData = GetData();

uint rowIdx = 4;
foreach (var item in currentAccountData)

    OpenXML.SetCellValue(spreadsheet, worksheet, 1, rowIdx, CellValues.String, item.TypeDoc, _generalStyle, true);
    OpenXML.SetCellValue(spreadsheet, worksheet, 2, rowIdx, CellValues.String, item.NrDoc, _generalStyle, true);
    if (item.DocValue != null)
        OpenXML.SetCellValue(spreadsheet, worksheet, 3, rowIdx, Convert.ToDouble(item.DocValue), _currencyStyle, true);
    if (item.PendingValue != null)
        OpenXML.SetCellValue(spreadsheet, worksheet, 4, rowIdx, Convert.ToDouble(item.PendingValue), _currencyStyle, true);
    if (item.RecordDate != null)
        OpenXML.SetCellValue(spreadsheet, worksheet, 5, rowIdx, item.RecordDate, _dateStyle, true);
    if (item.SalaryDate != null)
        OpenXML.SetCellValue(spreadsheet, worksheet, 6, rowIdx, item.SalaryDate, _dateStyle, true);

    rowIdx++;

然后创建表格部分

TableParts tableParts1 = new TableParts()  Count = (uint)1U ;
TablePart tablePart1 = new TablePart()  Id = "rId1" ;
tableParts1.Append(tablePart1);
worksheet.Append(tableParts1);

之后,我使用 OpenXML.CreateTable 方法

OpenXML.CreateTable(spreadsheet, worksheet, "table1", 3U, 1U, (uint)currentAccountData.Count + 3, 6U);

我做错了什么?

如果您需要更多代码,我将上传应用程序。 谢谢。

编辑:

当我打开excel时它说:

已删除部分:/xl/tables/table.xml 部分包含 XML 错误。 (表)A 文档必须只包含一个根元素。第 1 行,第 0 列。

【问题讨论】:

发生了什么或没有发生什么?你有错误吗?它说什么?您是否尝试过将 Open XML Productivity Tool 与您要创建的工作簿模型一起使用?它将为您提供构建此类工作簿的代码。 @MichaelGunter 对不起,迈克尔,我忘了发布错误...我使用生产力工具检查了这些表是如何创建的。代码类似,但不适用于本示例。 在我看来,TablePart (tablePart1) 需要一些内容,但您没有提供它(生成的 XML 没有根元素)。 @MichaelGunter 这就是我所坚持的......但是通过生产力工具生成的 TablePart 也没有得到任何东西,但它可以工作。生成的 Excel 类:pastebin.com/jBTG6zgi 抱歉将其发布在其他网站上。 @MichaelGunter 好吧,如果我删除了表格部分,它不会给出任何错误,但表格也没有创建 【参考方案1】:

我做错了什么?

您的调试方法对我来说似乎是错误的。我建议以下之一:

一个。将生成的 xml 与手工制作的 xlsx 文件进行比较。 乙。从代码开始,由 OpenXML 生产力工具生成(所以它 在您的应用程序中生成静态表)并修改/重构它 逐步使用来自您的应用程序的动态数据并匹配您的编码标准 - 这样您就可以发现您的 一次迭代出错,或者只是得到一个干净的工作解决方案

【讨论】:

以上是关于OpenXML 动态创建“表/数据透视表”的主要内容,如果未能解决你的问题,请参考以下文章

Excel 数据透视表空白类别未正确显示

数据分析处理——透析表和交叉表

2022年最新Python大数据之Excel基础

数据模型表在数据透视表字段列表中可见,但在数据模型本身中不可见 - Excel 2016

手把手教你玩转 Excel 数据透视表

Laravel Eloquent - 查询数据透视表