我正在尝试使用C#OpenXML Power工具以编程方式生成数据透视表。我正在尝试将原始数据导出到工作表1和工作表1上的数据透视表。 当我将整数列添加为数据值时,将使用适当的值生成数据透视表。但是,如果我选择一个非整数列,则生成的计数和总和始终为零。以下是其生成的excel文件的快照。
Pivot.txt中的数据采用以下格式: 年,季度,地区,类别,产品,金额 2010,Q1,North,Bicycles,B100,3448.00 2010,Q1,North,Bicycles,B200,8448.00 2010,Q1,North,Bicycles,B300,922.00 2010,Q1,North,配件,镜子,303.00 2010,Q1,北部,配件,载体,455.00 2010,Q1,South,Bicycles,B100,2887.00 2010,Q1,South,Bicycles,B200,4477.00 2010,Q1,South,Bicycles,B300,1011.00 2010,Q1,南方,配件,镜子,80.00 2010,Q1,南方,配件,载体205.00
以下是我正在使用的代码:
private static void generatePivot()
{
int row;
row = 1;
int maxColumn = 1;
using (OpenXmlMemoryStreamDocument streamDoc = OpenXmlMemoryStreamDocument.CreateSpreadsheetDocument())
{
using (SpreadsheetDocument doc = streamDoc.GetSpreadsheetDocument())
{
WorksheetPart sheet = WorksheetAccessor.AddWorksheet(doc, "Range");
using (System.IO.StreamReader source = new System.IO.StreamReader("../../PivotData.txt"))
{
while (!source.EndOfStream)
{
string line = source.ReadLine();
if (line.Length > 3)
{
string[] fields = line.Split(',');
int column = 1;
foreach (string item in fields)
{
double num;
if (double.TryParse(item, out num))
WorksheetAccessor.SetCellValue(doc, sheet, row, column++, num);
else
WorksheetAccessor.SetCellValue(doc, sheet, row, column++, item);
}
maxColumn = column - 1;
}
row++;
}
}
sheet.PutXDocument();
WorksheetAccessor.SetRange(doc, "Sales", "Range", 1, 1, row - 1, maxColumn);
WorksheetPart pivot = WorksheetAccessor.AddWorksheet(doc, "Pivot");
WorksheetAccessor.CreatePivotTable(doc, "Sales", pivot);
// Configure pivot table rows, columns, data and filters
//WorksheetAccessor.AddPivotAxis(doc, pivot, "Year", WorksheetAccessor.PivotAxis.Column);
WorksheetAccessor.AddPivotAxis(doc, pivot, "Quarter", WorksheetAccessor.PivotAxis.Column);
WorksheetAccessor.AddPivotAxis(doc, pivot, "Category", WorksheetAccessor.PivotAxis.Row);
//WorksheetAccessor.AddPivotAxis(doc, pivot, "Product", WorksheetAccessor.PivotAxis.Row);
WorksheetAccessor.AddDataValue(doc, pivot, "Product");
WorksheetAccessor.AddPivotAxis(doc, pivot, "Region", WorksheetAccessor.PivotAxis.Page);
}
streamDoc.GetModifiedSmlDocument().SaveAs("../../NewPivot.xlsx");
}
}