Pivot – 旋转 unclear – 不清楚 grouping – 分组 remove – 移除 result – 结果 rows – 行

huangapple go评论62阅读模式
英文:

Pivot unclear grouping / remove result rows

问题

我遇到了理解POI中的数据透视表的问题。我可以生成一个紧凑的数据透视表,但仍然有问题,不知道如何删除结果行(红色标记的行)。

这些行的名称是什么?也许我可以通过搜索它们来找到它们。

创建数据透视表的代码:

import java.io.FileOutputStream;
import org.apache.poi.ss.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.xssf.usermodel.*;

public class CreatePivotTableComplex {

 public static void main(String[] args) throws Exception {

  try (Workbook workbook = new XSSFWorkbook(); 
       FileOutputStream fileout = new FileOutputStream("Excel.xlsx")) {

   Sheet pivotSheet = workbook.createSheet("Pivot");
   Sheet dataSheet = workbook.createSheet("Data");

   Row row;
   Cell cell;
   Object[][] data = new Object[][]{
    new Object[]{"Name", "Country", "Count", "Value", "Date"},
    new Object[]{"A", "C1", 2d, 123.56, "2023-05-22"},
    new Object[]{"B", "C1", 4d, 34.56, "2023-05-23"},
    new Object[]{"A", "C2", 1d, 56.78, "2023-05-24"},
    new Object[]{"B", "C2", 7d, 23.45, "2023-05-25"},
    new Object[]{"A", "C1", 3d, 234.56, "2023-05-26"},
    new Object[]{"A", "C1", 2d, 132.56, "2023-05-27"},
    new Object[]{"B", "C1", 5d, 78.90, "2023-05-28"}
   };
   for (int r = 0; r < data.length; r++) {
      row = dataSheet.createRow(r);
      Object[] rowData = data[r];
      for (int c = 0; c < rowData.length; c++) {
         cell = row.createCell(c);
         if (rowData[c] instanceof String) {
            cell.setCellValue((String) rowData[c]);
         } else if (rowData[c] instanceof Double) {
            cell.setCellValue((Double) rowData[c]);
         }
      }
   }

   AreaReference areaReference =
         new AreaReference(new CellReference(0, 0), new CellReference(data.length - 1, data[0].length - 1), SpreadsheetVersion.EXCEL2007);

   XSSFPivotTable pivotTable = ((XSSFSheet) pivotSheet).createPivotTable(areaReference, new CellReference("A4"), dataSheet);

   pivotTable.addRowLabel(0);
   pivotTable.addRowLabel(1);
   pivotTable.addRowLabel(4);
   pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 2, "Sum of count");
   pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 3, "Sum of value");

   pivotTable.getCTPivotTableDefinition().getPivotTableStyleInfo().setName("PivotStyleDark7");

   pivotTable.getCTPivotTableDefinition().setCompact(false);
   pivotTable.getCTPivotTableDefinition().setCompactData(false);
   pivotTable.getCTPivotTableDefinition().setGridDropZones(false);

   pivotTable.getCTPivotTableDefinition().setRowGrandTotals(false);

    pivotTable.getCTPivotTableDefinition().setColGrandTotals(true);
    pivotTable.getCTPivotTableDefinition().setRowGrandTotals(true);
    pivotTable.getCTPivotTableDefinition().setEnableDrill(false);

   // pivotTable.getCTPivotTableDefinition().setMultipleFieldFilters(false);
   // pivotTable.getCTPivotTableDefinition().setItemPrintTitles(true);
   for (org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotField pivotField : pivotTable.getCTPivotTableDefinition().getPivotFields()
         .getPivotFieldList()) {
      pivotField.setCompact(false);
      pivotField.setOutline(false);
   }

   workbook.write(fileout);

  }

 }
}
英文:

I am having issues to understand the pivot table in POI
I could generate a compact pivot, but I have still issues to identify how to remove the result rows (red marked)

Pivot – 旋转
unclear – 不清楚
grouping – 分组
remove – 移除
result – 结果
rows – 行

how are these rows named? So maybe I could have found them by searching for them.

the code which is creating the table:

import java.io.FileOutputStream;
import org.apache.poi.ss.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.xssf.usermodel.*;
public class CreatePivotTableComplex {
public static void main(String[] args) throws Exception {
try (Workbook workbook = new XSSFWorkbook(); 
FileOutputStream fileout = new FileOutputStream(&quot;Excel.xlsx&quot;) ) {
Sheet pivotSheet = workbook.createSheet(&quot;Pivot&quot;);
Sheet dataSheet = workbook.createSheet(&quot;Data&quot;);
Row row;
Cell cell;
Object[][] data = new Object[][]{
new Object[]{&quot;Name&quot;, &quot;Country&quot;, &quot;Count&quot;, &quot;Value&quot;, &quot;Date&quot;},
new Object[]{&quot;A&quot;, &quot;C1&quot;, 2d, 123.56, &quot;2023-05-22&quot;},
new Object[]{&quot;B&quot;, &quot;C1&quot;, 4d, 34.56, &quot;2023-05-23&quot;},
new Object[]{&quot;A&quot;, &quot;C2&quot;, 1d, 56.78, &quot;2023-05-24&quot;},
new Object[]{&quot;B&quot;, &quot;C2&quot;, 7d, 23.45, &quot;2023-05-25&quot;},
new Object[]{&quot;A&quot;, &quot;C1&quot;, 3d, 234.56, &quot;2023-05-26&quot;},
new Object[]{&quot;A&quot;, &quot;C1&quot;, 2d, 132.56, &quot;2023-05-27&quot;},
new Object[]{&quot;B&quot;, &quot;C1&quot;, 5d, 78.90, &quot;2023-05-28&quot;}
};
for (int r = 0; r &lt; data.length; r++) {
row = dataSheet.createRow(r);
Object[] rowData = data[r];
for (int c = 0; c &lt; rowData.length; c++) {
cell = row.createCell(c);
if (rowData[c] instanceof String) {
cell.setCellValue((String) rowData[c]);
} else if (rowData[c] instanceof Double) {
cell.setCellValue((Double) rowData[c]);
}
}
}
AreaReference areaReference =
new AreaReference(new CellReference(0, 0), new CellReference(data.length - 1, data[0].length - 1), SpreadsheetVersion.EXCEL2007);
XSSFPivotTable pivotTable = ((XSSFSheet) pivotSheet).createPivotTable(areaReference, new CellReference(&quot;A4&quot;), dataSheet);
pivotTable.addRowLabel(0);
pivotTable.addRowLabel(1);
pivotTable.addRowLabel(4);
pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 2, &quot;Sum of count&quot;);
pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 3, &quot;Sum of value&quot;);
pivotTable.getCTPivotTableDefinition().getPivotTableStyleInfo().setName(&quot;PivotStyleDark7&quot;);
pivotTable.getCTPivotTableDefinition().setCompact(false);
pivotTable.getCTPivotTableDefinition().setCompactData(false);
pivotTable.getCTPivotTableDefinition().setGridDropZones(false);
pivotTable.getCTPivotTableDefinition().setRowGrandTotals(false);
pivotTable.getCTPivotTableDefinition().setColGrandTotals(true);
pivotTable.getCTPivotTableDefinition().setRowGrandTotals(true);
pivotTable.getCTPivotTableDefinition().setEnableDrill(false);
// pivotTable.getCTPivotTableDefinition().setMultipleFieldFilters(false);
// pivotTable.getCTPivotTableDefinition().setItemPrintTitles(true);
for (org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotField pivotField : pivotTable.getCTPivotTableDefinition().getPivotFields()
.getPivotFieldList()) {
pivotField.setCompact(false);
pivotField.setOutline(false);
}
workbook.write(fileout);
}
}

答案1

得分: 1

以下是您提供的代码的翻译部分:

"Those totals are properties of the pivot table fields, not of the whole table. Only grand totals are properties of the whole table.

But much pivot field properties can only be set if a proper pivot table definition and pivot table cache definition is present. Neither the one nor the other can Apache POI create so far.

See https://stackoverflow.com/questions/40354088/how-to-set-default-value-in-apache-poi-pivot-table-report-filter/40359542#40359542, https://stackoverflow.com/questions/37305976/apache-poi-xssfpivottable-setdefaultsubtotal/40480654#40480654 and https://stackoverflow.com/questions/60887605/java-how-to-create-a-pivot-with-apache-poi/60891686#60891686.

Following uses my addRowLabel method to extend XSSFPivotTable.addRowLabel to provide semi-proper pivot table definition and pivot table cache definition per field.

Complete example:

<!-- language: java -->

import java.io.FileOutputStream;

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

class CreatePivotTableClassicLayoutNoFieldSubTotals {

static void addRowLabel(XSSFPivotTable pivotTable, Sheet dataSheet, AreaReference areaReference, int column,
boolean defaultSubtotals) {

DataFormatter formatter = new DataFormatter(java.util.Locale.US);
//create row label - apache poi creates as much fields for each as rows are in the pivot table data range
pivotTable.addRowLabel(column);

//determine unique labels in column
java.util.TreeSet<String> uniqueItems = new java.util.TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
for (int r = areaReference.getFirstCell().getRow()+1; r < areaReference.getLastCell().getRow()+1; r++) {
uniqueItems.add(formatter.formatCellValue(dataSheet.getRow(r).getCell(column)));
}
//System.out.println(uniqueItems);

//build pivot table and cache
org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotField ctPivotField
= pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(column);
int i = 0;
for (String item : uniqueItems) {
//take the items as numbered items: <item x="0"/><item x="1"/>
ctPivotField.getItems().getItemArray(i).unsetT();
ctPivotField.getItems().getItemArray(i).setX((long)i);
//build a cache definition which has shared elements for those items
pivotTable.getPivotCacheDefinition().getCTPivotCacheDefinition().getCacheFields().getCacheFieldArray(column)
.getSharedItems().addNewS().setV(item);
i++;
}

//set pivot field settings
ctPivotField.setDefaultSubtotal(defaultSubtotals); // no subtotals for this field

//remove further items
if (ctPivotField.getDefaultSubtotal()) i++; //let one default item be if there shall be subtotals
for (int k = ctPivotField.getItems().getItemList().size()-1; k >= i; k--) {
ctPivotField.getItems().removeItem(k);
}
ctPivotField.getItems().setCount(i);

}

public static void main(String[] args) throws Exception {

try (Workbook workbook = new XSSFWorkbook();
FileOutputStream fileout = new FileOutputStream("./Excel.xlsx") ) {

Sheet pivotSheet = workbook.createSheet("Pivot");
Sheet dataSheet = workbook.createSheet("Data");

Row row;
Cell cell;
Object[][] data = new Object[][]{
new Object[]{"Name", "Country", "Count", "Value", "Date"},
new Object[]{"A", "C1", 2d, 123.56, "2023-05-22"},
new Object[]{"B", "C1", 4d, 34.56, "2023-05-23"},
new Object[]{"A", "C2", 1d, 56.78, "2023-05-24"},
new Object[]{"B", "C2", 7d, 23.45, "2023-05-25"},
new Object[]{"A", "C1", 3d, 234.56, "2023-05-26"},
new Object[]{"A", "C1", 2d, 132.56, "2023-05-27"},
new Object[]{"B", "C1", 5d, 78.90, "2023-05-28"}
};
for (int r = 0; r < data.length; r++) {
row = dataSheet.createRow(r);
Object[] rowData = data[r];
for (int c = 0; c < rowData.length; c++) {
cell = row.createCell(c);
if (rowData[c] instanceof String) {
cell.setCellValue((String) rowData[c]);
} else if (rowData[c] instanceof Double) {
cell.setCellValue((Double) rowData[c]);
}
}
}

AreaReference areaReference =
new AreaReference(new CellReference(0, 0), new CellReference(data.length - 1, data[0].length - 1),
SpreadsheetVersion.EXCEL2007);

XSSFPivotTable pivotTable = ((XSSFSheet) pivotSheet).createPivotTable(areaReference,
new CellReference("A4"), dataSheet);

// pivotTable.addRowLabel(0);
// pivotTable.addRowLabel(1);
// pivotTable.addRowLabel(4);
addRowLabel(pivotTable, dataSheet, areaReference, 0, false);
addRowLabel(pivotTable, dataSheet, areaReference, 1, false);
addRowLabel(pivotTable, dataSheet, areaReference, 4, false);

pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 2, "Sum of count");
pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 3, "Sum of value");

pivotTable.getCTPivotTableDefinition().getPivotTableStyleInfo().setName("PivotStyleDark7");

pivotTable.getCTPivotTableDefinition().setCompact(false);
pivotTable.getCTPivotTableDefinition().setCompactData(false);
pivotTable.getCTPivotTableDefinition().setGridDrop

英文:

Those totals are properties of the pivot table fields, not of the whole table. Only grand totals are properties of the whole table.

But much pivot field properties can only be set if a proper pivot table definition and pivot table cache definition is present. Neither the one nor the other can Apache POI create so far.

See https://stackoverflow.com/questions/40354088/how-to-set-default-value-in-apache-poi-pivot-table-report-filter/40359542#40359542, https://stackoverflow.com/questions/37305976/apache-poi-xssfpivottable-setdefaultsubtotal/40480654#40480654 and https://stackoverflow.com/questions/60887605/java-how-to-create-a-pivot-with-apache-poi/60891686#60891686.

Following uses my addRowLabel method to extend XSSFPivotTable.addRowLabel to provide semi-proper pivot table definition and pivot table cache definition per field.

Complete example:

<!-- language: java -->

import java.io.FileOutputStream;
import org.apache.poi.ss.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.xssf.usermodel.*;
class CreatePivotTableClassicLayoutNoFieldSubTotals {
static void addRowLabel(XSSFPivotTable pivotTable, Sheet dataSheet, AreaReference areaReference, int column, 
boolean defaultSubtotals) { 
DataFormatter formatter = new DataFormatter(java.util.Locale.US);
//create row label - apache poi creates as much fields for each as rows are in the pivot table data range
pivotTable.addRowLabel(column);
//determine unique labels in column
java.util.TreeSet&lt;String&gt; uniqueItems = new java.util.TreeSet&lt;String&gt;(String.CASE_INSENSITIVE_ORDER);
for (int r = areaReference.getFirstCell().getRow()+1; r &lt; areaReference.getLastCell().getRow()+1; r++) {
uniqueItems.add(formatter.formatCellValue(dataSheet.getRow(r).getCell(column)));
}
//System.out.println(uniqueItems);
//build pivot table and cache
org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotField ctPivotField 
= pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(column);
int i = 0;
for (String item : uniqueItems) {
//take the items as numbered items: &lt;item x=&quot;0&quot;/&gt;&lt;item x=&quot;1&quot;/&gt;
ctPivotField.getItems().getItemArray(i).unsetT();
ctPivotField.getItems().getItemArray(i).setX((long)i);
//build a cache definition which has shared elements for those items 
pivotTable.getPivotCacheDefinition().getCTPivotCacheDefinition().getCacheFields().getCacheFieldArray(column)
.getSharedItems().addNewS().setV(item);
i++;
}
//set pivot field settings
ctPivotField.setDefaultSubtotal(defaultSubtotals); // no subtotals for this field
//remove further items
if (ctPivotField.getDefaultSubtotal()) i++; //let one default item be if there shall be subtotals
for (int k = ctPivotField.getItems().getItemList().size()-1; k &gt;= i; k--) {
ctPivotField.getItems().removeItem(k);
}
ctPivotField.getItems().setCount(i);
}    
public static void main(String[] args) throws Exception {
try (Workbook workbook = new XSSFWorkbook(); 
FileOutputStream fileout = new FileOutputStream(&quot;./Excel.xlsx&quot;) ) {
Sheet pivotSheet = workbook.createSheet(&quot;Pivot&quot;);
Sheet dataSheet = workbook.createSheet(&quot;Data&quot;);
Row row;
Cell cell;
Object[][] data = new Object[][]{
new Object[]{&quot;Name&quot;, &quot;Country&quot;, &quot;Count&quot;, &quot;Value&quot;, &quot;Date&quot;},
new Object[]{&quot;A&quot;, &quot;C1&quot;, 2d, 123.56, &quot;2023-05-22&quot;},
new Object[]{&quot;B&quot;, &quot;C1&quot;, 4d, 34.56, &quot;2023-05-23&quot;},
new Object[]{&quot;A&quot;, &quot;C2&quot;, 1d, 56.78, &quot;2023-05-24&quot;},
new Object[]{&quot;B&quot;, &quot;C2&quot;, 7d, 23.45, &quot;2023-05-25&quot;},
new Object[]{&quot;A&quot;, &quot;C1&quot;, 3d, 234.56, &quot;2023-05-26&quot;},
new Object[]{&quot;A&quot;, &quot;C1&quot;, 2d, 132.56, &quot;2023-05-27&quot;},
new Object[]{&quot;B&quot;, &quot;C1&quot;, 5d, 78.90, &quot;2023-05-28&quot;}
};
for (int r = 0; r &lt; data.length; r++) {
row = dataSheet.createRow(r);
Object[] rowData = data[r];
for (int c = 0; c &lt; rowData.length; c++) {
cell = row.createCell(c);
if (rowData[c] instanceof String) {
cell.setCellValue((String) rowData[c]);
} else if (rowData[c] instanceof Double) {
cell.setCellValue((Double) rowData[c]);
}
}
}
AreaReference areaReference =
new AreaReference(new CellReference(0, 0), new CellReference(data.length - 1, data[0].length - 1), 
SpreadsheetVersion.EXCEL2007);
XSSFPivotTable pivotTable = ((XSSFSheet) pivotSheet).createPivotTable(areaReference, 
new CellReference(&quot;A4&quot;), dataSheet);
// pivotTable.addRowLabel(0);
// pivotTable.addRowLabel(1);
// pivotTable.addRowLabel(4);
addRowLabel(pivotTable, dataSheet, areaReference, 0, false);
addRowLabel(pivotTable, dataSheet, areaReference, 1, false);
addRowLabel(pivotTable, dataSheet, areaReference, 4, false);   
pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 2, &quot;Sum of count&quot;);
pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 3, &quot;Sum of value&quot;);
pivotTable.getCTPivotTableDefinition().getPivotTableStyleInfo().setName(&quot;PivotStyleDark7&quot;);
pivotTable.getCTPivotTableDefinition().setCompact(false);
pivotTable.getCTPivotTableDefinition().setCompactData(false);
pivotTable.getCTPivotTableDefinition().setGridDropZones(true);
// pivotTable.getCTPivotTableDefinition().setMultipleFieldFilters(false);
// pivotTable.getCTPivotTableDefinition().setItemPrintTitles(true);
for (org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotField pivotField : pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldList()) {
pivotField.setCompact(false);  
pivotField.setOutline(false);  
}
workbook.write(fileout);
}
}
}

huangapple
  • 本文由 发表于 2023年6月6日 14:32:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76411982.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定