Apache POI Pivot表错误,当列和行标签使用相同的索引时

时间:2016-11-02 22:39:23

标签: java excel apache-poi pivot pivot-table

我正在尝试创建一个数据透视表来进行群组分析

.lm_controls

这是在打开文件时发生错误,文件已损坏你想要打开文件吗?当我说是并打开它时,结果看起来很好,唯一的问题是错误。

我做了一个变通方法,以获得具有不同名称的重复列数据

代表: 说第1列是电子邮件添加了一个重复的列36与名称重复电子邮件,并如下所示,它工作正常

.lm_tab {
  height: 40px !important;
  line-height:40px;
}

.lm_close_tab {
  height: 35px !important;
}

.lm_controls {
  top:13px;
}

为什么在我将列和行标签都指定为1时首先失败了。

非常感谢任何帮助

1 个答案:

答案 0 :(得分:3)

如果你使用apache poi设置pivotTable.addRowLabel(1),那么apache poi只将pivot field 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();
  }
 }
}
相关问题