簡體   English   中英

當列和行標簽使用相同的索引時,Apache POI數據透視表錯誤

[英]Apache POI Pivot table error when same index is used for both column and row label

我正在嘗試創建數據透視表以進行同類群組分析

pivotTable.addColumnLabel(DataConsolidateFunction.COUNT, 1);
pivotTable.addRowLabel(1);

這在打開文件時給我一個錯誤,表明文件已損壞,您是否仍要打開文件,當我說“是”並打開它時,結果看起來很好,唯一的問題是錯誤。

我做了一個變通辦法以使重復的列數據具有不同的名稱

例如:說第1列是電子郵件,添加了一個重復的第36列,名稱為dup email,並且如下所示,它工作正常

pivotTable.addColumnLabel(DataConsolidateFunction.COUNT, 1);
pivotTable.addRowLabel(35);

為什么首先我將列和行標簽都設為1卻失敗了

任何幫助是極大的贊賞

如果您使用apache poi設置pivotTable.addRowLabel(1) ,則apache poi僅將樞軸字段1設置為axisRow,但如果您還希望對pivotTable.addColumnLabel(DataConsolidateFunction.COUNT, 1)也必須是dataField。 因此,我們需要糾正這一點。

例:

import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;

import java.io.*;

class PivotTableTest5 {

 private static void setCellData(Sheet sheet) {
  Row row = sheet.createRow(0);
  Cell cell = row.createCell(0);
  cell.setCellValue("Name");
  cell = row.createCell(1);
  cell.setCellValue("City");

  for (int r = 1; r < 15; r++) {
   row = sheet.createRow(r);
   cell = row.createCell(0);
   cell.setCellValue("Name " + ((r-1) % 4 + 1));
   cell = row.createCell(1);
   cell.setCellValue("City " + (int)((new java.util.Random().nextDouble() * 3)+1) );  
  }
 }

 public static void main(String[] args) {
  try {
   XSSFWorkbook wb = new XSSFWorkbook();
   XSSFSheet sheet = wb.createSheet();

   //Create some data to build the pivot table on
   setCellData(sheet);

   XSSFPivotTable pivotTable = sheet.createPivotTable(
    new AreaReference(new CellReference("A1"), new CellReference("B15")), new CellReference("H5"));
   //Count the second column. This needs to be second column a data field.
   pivotTable.addColumnLabel(DataConsolidateFunction.COUNT, 1);
   //Use second column as row label
   pivotTable.addRowLabel(1);
   //Apache poi sets pivot field 1 (second column) only to be axisRow but it needs to be dataField too.
   pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(1).setDataField(true);

   FileOutputStream fileOut = new FileOutputStream("PivotTableTest5.xlsx");
   wb.write(fileOut);
   fileOut.close();
   wb.close();
  } catch (FileNotFoundException e) {
    e.printStackTrace();
  } catch (IOException e) {
    e.printStackTrace();
  }
 }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM