OpenXml数据透视表:如何读取总表和小表才能显示?

问题描述 投票:0回答:1

我正在尝试使用OpenXml完全从头开始创建一个Excel数据透视表。

我已经成功地创建了透视表本身(创建了一个PivotTable定义,一个缓存定义,所有的缓存记录,pivotFields,RowItems,等等等等)。

但我如何 展示 的任何数据? 如何读取PivotTable的计算结果,以便将这些值写入单元格?

例如:"总计 "是86,631.62美元。

Example Pivot Table definition and Pivot Table data

  • "总金额 "是86,631. 62美元。
  • 两个小计是$61,631,12和$25,000.50。

当我查看XML中的 xl\worksheets\sheet2.xml这些值都是 "硬编码 "到单元格中的,如果我自己创建单元格(使用OpenXml),那么我如何 "查询 "这些值,让Pivot表为我计算?

如果我自己创建单元格(使用OpenXml),那么我如何 "查询 "这些值,让Pivot表为我计算?

PS:我一直在广泛地使用OpenXml生产力工具......但它也只是 "硬编码 "总计和小计......没有给出任何线索,这些值实际上是如何计算的。

c# excel pivot-table openxml
1个回答
4
投票

如果你不想使用EPPlus,你可以使用单元格公式。

cell.DataType = new EnumValue<CellValue.Number);
cell.CellFormula = new CellFormula($"=SUBTOTAL{"109"}{rowName}");

//force full recalculation of the cells
workbookPart.workbook.CalculationProperties.ForceFullCalculation = true;
workbookPart.workbook.CalculationProperties.FullCalculationLoad = true;

这样你就可以通过OpenXml使用每个公式来计算任何你需要的东西。

为了加载到DataTable中。

DataTable dt = new DataTable();

using (SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open(@"..\..\example.xlsx", false))
{

    WorkbookPart workbookPart = spreadSheetDocument.WorkbookPart;
    IEnumerable<Sheet> sheets = spreadSheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();
    string relationshipId = sheets.First().Id.Value;
    WorksheetPart worksheetPart = (WorksheetPart)spreadSheetDocument.WorkbookPart.GetPartById(relationshipId);
    Worksheet workSheet = worksheetPart.Worksheet;
    SheetData sheetData = workSheet.GetFirstChild<SheetData>();
    IEnumerable<Row> rows = sheetData.Descendants<Row>();

    foreach (Cell cell in rows.ElementAt(0))
    {
        dt.Columns.Add(GetCellValue(spreadSheetDocument, cell));
    }

    foreach (Row row in rows) //this will also include your header row...
    {
        DataRow tempRow = dt.NewRow();

        for (int i = 0; i < row.Descendants<Cell>().Count(); i++)
        {
            tempRow[i] = GetCellValue(spreadSheetDocument, row.Descendants<Cell>().ElementAt(i-1));
        }

        dt.Rows.Add(tempRow);
    }

}

© www.soinside.com 2019 - 2024. All rights reserved.