Java 在通过ApachePOI添加计算字段时,我遇到了一个问题
我正试图通过ApachePOI添加计算字段,当只有一个非计算字段,其余字段是计算字段时,我面临问题。我在打开excel工作表时出错,如下所示 但当有多个非计算字段时,excel工作表不会抛出任何错误,计算字段显示良好 这是我的密码:Java 在通过ApachePOI添加计算字段时,我遇到了一个问题,java,excel,apache-poi,calculated-columns,Java,Excel,Apache Poi,Calculated Columns,我正试图通过ApachePOI添加计算字段,当只有一个非计算字段,其余字段是计算字段时,我面临问题。我在打开excel工作表时出错,如下所示 但当有多个非计算字段时,excel工作表不会抛出任何错误,计算字段显示良好 这是我的密码: public static void main(String[] args) throws FileNotFoundException, IOException, InvalidFormatException { createPivotTable(
public static void main(String[] args) throws FileNotFoundException, IOException, InvalidFormatException {
createPivotTable();
}
private static void createPivotTable() throws IOException, FileNotFoundException {
try (XSSFWorkbook wb = new XSSFWorkbook()) {
XSSFSheet sheet = wb.createSheet("1econtent");
XSSFSheet sheet1 = wb.createSheet("1e");
sheet1.setDisplayGridlines(false);
setCellData(sheet,wb);
AreaReference source = new AreaReference("A1:F5", SpreadsheetVersion.EXCEL2007);
CellReference position = new CellReference(0,0);
XSSFPivotTable pivotTable = sheet1.createPivotTable(source, position,wb.getSheet("1econtent"));
pivotTable.addRowLabel(2);
pivotTable.addRowLabel(0);
pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 3);
CTCacheFields ctCacheFields = pivotTable.getPivotCacheDefinition().getCTPivotCacheDefinition().getCacheFields();
CTCacheField ctCacheField = ctCacheFields.addNewCacheField();
ctCacheField.setName("Field");
ctCacheField.setFormula("'Actuals' / 'Estimates'");
ctCacheField.setDatabaseField(false);
ctCacheFields.setCount(ctCacheFields.sizeOfCacheFieldArray());
CTPivotField pivotField = pivotTable.getCTPivotTableDefinition().getPivotFields().addNewPivotField();
pivotField.setDataField(true);
pivotField.setDragToCol(false);
pivotField.setDragToPage(false);
pivotField.setDragToRow(false);
pivotField.setShowAll(false);
pivotField.setDefaultSubtotal(false);
CTDataFields dataFields;
if(pivotTable.getCTPivotTableDefinition().getDataFields() != null) {
dataFields = pivotTable.getCTPivotTableDefinition().getDataFields();
} else {
dataFields = pivotTable.getCTPivotTableDefinition().addNewDataFields();
}
CTDataField dataField = dataFields.addNewDataField();
dataField.setName("Calculated Field");
dataField.setFld(pivotTable.getPivotCacheDefinition().getCTPivotCacheDefinition().getCacheFields().getCount()-1);
dataField.setBaseItem(0);
dataField.setBaseField(0);
DataFormat dataformat = pivotTable.getParentSheet().getWorkbook().createDataFormat();
short numFmtId = dataformat.getFormat("0.0%");
dataField.setNumFmtId(numFmtId);
try (FileOutputStream fileOut = new FileOutputStream("Output.xlsx")) {
wb.write(fileOut);
}
}
}
public static void setCellData(XSSFSheet sheet,XSSFWorkbook wb){
Row row1 = sheet.createRow(0);
// Create a cell and put a value in it.
Cell cell11 = row1.createCell(0);
cell11.setCellValue("Names");
Cell cell12 = row1.createCell(1);
cell12.setCellValue("Age");
Cell cell13 = row1.createCell(2);
cell13.setCellValue("Dept");
Cell cell14 = row1.createCell(3);
cell14.setCellValue("Salary");
Cell cell15 = row1.createCell(4);
cell15.setCellValue("Actuals");
Cell cell16 = row1.createCell(5);
cell16.setCellValue("Estimates");
Row row2 = sheet.createRow(1);
Cell cell21 = row2.createCell(0);
cell21.setCellValue("Adam");
Cell cell22 = row2.createCell(1);
cell22.setCellValue(22);
Cell cell23 = row2.createCell(2);
cell23.setCellValue("Sales");
Cell cell24 = row2.createCell(3);
cell24.setCellValue(10);
Cell cell25 = row2.createCell(4);
cell25.setCellValue(12);
Cell cell26 = row2.createCell(5);
cell26.setCellValue(60);
Row row3 = sheet.createRow(2);
Cell cell31 = row3.createCell(0);
cell31.setCellValue("Bran");
Cell cell32 = row3.createCell(1);
cell32.setCellValue(24);
Cell cell33 = row3.createCell(2);
cell33.setCellValue("Finance");
Cell cell34 = row3.createCell(3);
cell34.setCellValue(20);
Cell cell35 = row3.createCell(4);
cell35.setCellValue(24);
Cell cell36 = row3.createCell(5);
cell36.setCellValue(60);
Row row4 = sheet.createRow(3);
Cell cell41 = row4.createCell(0);
cell41.setCellValue("Jane");
Cell cell42 = row4.createCell(1);
cell42.setCellValue(23);
Cell cell43 = row4.createCell(2);
cell43.setCellValue("IT");
Cell cell44 = row4.createCell(3);
cell44.setCellValue(30);
Cell cell45 = row4.createCell(4);
cell45.setCellValue(30);
Cell cell46 = row4.createCell(5);
cell46.setCellValue(60);
Row row5 = sheet.createRow(4);
Cell cell211 = row5.createCell(0);
cell211.setCellValue("Dave");
Cell cell221 = row5.createCell(1);
cell221.setCellValue(30);
Cell cell231 = row5.createCell(2);
cell231.setCellValue("Sales");
Cell cell241 = row5.createCell(3);
cell241.setCellValue(50);
Cell cell251 = row5.createCell(4);
cell251.setCellValue(6);
Cell cell261 = row5.createCell(5);
cell261.setCellValue(60);
}
添加一个或多个列标签时没有错误。有人能帮我做这个吗
预期输出仅为一个非计算列和一个计算列,如下所示
在透视表定义中有一个元素
colFields
,如果有多个数据字段作为列字段,则该元素至少需要一个字段。但是apachepoi
如果只设置了一个列标签,则不会添加该字段,因为如果只存在一个列字段,则不需要添加该字段
但由于您在较低级别添加了一个数据字段作为列字段,因此它缺少colFields
字段。这就是在Excel
中打开文件时出错的原因
如果设置了多个列标签,则apachepoi
会添加colFields
字段。这就是为什么它会起作用
因此,在低级别创建数据字段后,在代码中添加以下内容:
...
// at least one field in colFields is needed if there are multiple data fields
CTColFields colFields;
if(pivotTable.getCTPivotTableDefinition().getColFields() != null) {
colFields = pivotTable.getCTPivotTableDefinition().getColFields();
} else {
colFields = pivotTable.getCTPivotTableDefinition().addNewColFields();
}
CTField field;
if (colFields.getFieldList().size() == 0) {
field = colFields.addNewField();
field.setX(-2);
}
...
这将添加一个新的colFields
元素(如果尚未存在)。它在那里添加字段
元素(如果还没有)
再举一个完整的例子:
import java.io.FileOutputStream;
import org.apache.poi.ss.SpreadsheetVersion;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.xssf.usermodel.*;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.*;
class CreatePivotTableCalculatedFields {
public static void main(String[] args) throws Exception {
createPivotTable();
}
private static void createPivotTable() throws Exception {
try (XSSFWorkbook wb = new XSSFWorkbook();
FileOutputStream fileOut = new FileOutputStream("Output.xlsx")) {
XSSFSheet dataSheet = wb.createSheet("1econtent");
XSSFSheet pivotSheet = wb.createSheet("1e");
setCellData(dataSheet, wb);
AreaReference source = new AreaReference("A1:F5", SpreadsheetVersion.EXCEL2007);
CellReference position = new CellReference(0,0);
XSSFPivotTable pivotTable = pivotSheet.createPivotTable(source, position,wb.getSheet("1econtent"));
pivotTable.addRowLabel(2);
pivotTable.addRowLabel(0);
pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 3);
pivotSheet.setDisplayGridlines(false);
wb.setSelectedTab(1);
wb.setActiveSheet(1);
// customize pivot table
CTCacheFields ctCacheFields = pivotTable.getPivotCacheDefinition().getCTPivotCacheDefinition().getCacheFields();
CTCacheField ctCacheField = ctCacheFields.addNewCacheField();
ctCacheField.setName("Field");
ctCacheField.setFormula("'Actuals' / 'Estimates'");
ctCacheField.setDatabaseField(false);
ctCacheFields.setCount(ctCacheFields.sizeOfCacheFieldArray());
CTPivotField pivotField = pivotTable.getCTPivotTableDefinition().getPivotFields().addNewPivotField();
pivotField.setDataField(true);
pivotField.setDragToCol(false);
pivotField.setDragToPage(false);
pivotField.setDragToRow(false);
pivotField.setShowAll(false);
pivotField.setDefaultSubtotal(false);
CTDataFields dataFields;
if(pivotTable.getCTPivotTableDefinition().getDataFields() != null) {
dataFields = pivotTable.getCTPivotTableDefinition().getDataFields();
} else {
dataFields = pivotTable.getCTPivotTableDefinition().addNewDataFields();
}
CTDataField dataField = dataFields.addNewDataField();
dataField.setName("Calculated Field");
dataField.setFld(pivotTable.getPivotCacheDefinition().getCTPivotCacheDefinition().getCacheFields().getCount()-1);
dataField.setBaseItem(0);
dataField.setBaseField(0);
DataFormat dataformat = pivotTable.getParentSheet().getWorkbook().createDataFormat();
short numFmtId = dataformat.getFormat("0.0%");
dataField.setNumFmtId(numFmtId);
// at least one field in colFields is needed if there are multiple data fields
CTColFields colFields;
if(pivotTable.getCTPivotTableDefinition().getColFields() != null) {
colFields = pivotTable.getCTPivotTableDefinition().getColFields();
} else {
colFields = pivotTable.getCTPivotTableDefinition().addNewColFields();
}
CTField field;
if (colFields.getFieldList().size() == 0) {
field = colFields.addNewField();
field.setX(-2);
}
wb.write(fileOut);
}
}
public static void setCellData(XSSFSheet sheet, XSSFWorkbook wb){
Object[][] data = new Object[][] {
new Object[] {"Names", "Age", "Dept", "Salary", "Actuals", "Estimates"},
new Object[] {"Adam", 22d, "Sales", 10d, 12d, 60d},
new Object[] {"Bran", 24d, "Finance", 20d, 24d, 60d},
new Object[] {"Jane", 23d, "IT", 30d, 30d, 60d},
new Object[] {"Dave", 30d, "Sales", 50d, 6d, 60d}
};
XSSFRow row;
XSSFCell cell;
for (int r = 0; r < data.length; r++) {
row = sheet.createRow(r);
for (int c = 0 ; c < data[r].length; c++) {
cell = row.createCell(c);
if (data[r][c] instanceof String) {
cell.setCellValue((String)data[r][c]);
} else if (data[r][c] instanceof Double) {
cell.setCellValue((Double)data[r][c]);
}
}
}
}
}
import java.io.FileOutputStream;
导入org.apache.poi.ss.SpreadsheetVersion;
导入org.apache.poi.ss.usermodel.*;
导入org.apache.poi.ss.util.*;
导入org.apache.poi.xssf.usermodel.*;
导入org.openxmlformats.schemas.spreadsheetml.x2006.main.*;
类CreatePivotTableCalculatedFields{
公共静态void main(字符串[]args)引发异常{
创建数据透视表();
}
私有静态void createPivotTable()引发异常{
try(XSSFWorkbook wb=newxssfworkbook();
FileOutputStream fileOut=新的FileOutputStream(“Output.xlsx”)){
XSSFSheet数据表=wb.createSheet(“1econtent”);
XSSFSheet数据透视表=wb.createSheet(“1e”);
setCellData(数据表,wb);
AreaReference source=新的AreaReference(“A1:F5”,电子表格版本.EXCEL2007);
CellReference位置=新的CellReference(0,0);
XSSFPivotTable pivotTable=pivotSheet.createPivotTable(源、位置、wb.getSheet(“1econtent”);
数据透视表.addRowLabel(2);
数据透视表.addRowLabel(0);
数据透视表.addColumnLabel(DataConsolidateFunction.SUM,3);
数据透视表.setDisplayGridlines(false);
wb.setSelectedTab(1);
wb.setActiveSheet(1);
//自定义数据透视表
CTCacheFields CTCacheFields=数据透视表.getPivotCacheDefinition().getCTPivotCacheDefinition().getCacheFields();
CTCacheField CTCacheField=ctCacheFields.addNewCacheField();
ctCacheField.setName(“字段”);
setFormula(“实际值”/“估计值”);
ctCacheField.setDatabaseField(false);
ctCacheFields.setCount(ctCacheFields.sizeOfCacheFieldArray());
CTPivotField pivotField=数据透视表。getCTPivotTableDefinition().getPivotFields().addNewPivotField();
pivotField.setDataField(true);
pivotField.setDragToCol(false);
pivotField.setDragToPage(假);
pivotField.setDragToRow(false);
pivotField.setShowAll(假);
pivotField.setDefaultSubtotal(false);
CTDataFields数据字段;
if(数据透视表.getCTPivotTableDefinition().getDataFields()!=null){
数据字段=数据透视表.getCTPivotTableDefinition().getDataFields();
}否则{
数据字段=数据透视表。getCTPivotTableDefinition().addNewDataFields();
}
CTDataField dataField=dataFields.addNewDataField();
dataField.setName(“计算字段”);
dataField.setFld(数据透视表.getPivotCacheDefinition().getCTPivotCacheDefinition().getCacheFields().getCount()-1);
数据字段。setBaseItem(0);
dataField.setBaseField(0);
DataFormat DataFormat=数据透视表.getParentSheet().getWorkbook().createDataFormat();
短numFmtId=dataformat.getFormat(“0.0%”);
dataField.setNumFmtId(numFmtId);
//如果有多个数据字段,则colFields中至少需要一个字段
科菲尔德;
if(数据透视表.getCTPivotTableDefinition().getColFields()!=null){
colFields=pivotTable.getCTPivotTableDefinition().getColFields();
}否则{
colFields=数据透视表。getCTPivotTableDefinition().addNewColFields();
}
CTField字段;
if(colFields.getFieldList().size()==0){
field=colFields.addNewField();
字段setX(-2);
}
wb.写入(文件输出);
}
}
公共静态void setCellData(XSSFSheet工作表,XSSFWorkbook wb){
对象[][]数据=新对象[][]{
新对象[]{“姓名”、“年龄”、“部门”、“工资”、“实际值”、“估计值”},
新对象[]{“Adam”,22d,“Sales”,10d,12d,60d},
新对象[]{“Bran”,24d,“金融”,20d,24d,60d},
新对象[]{“Jane”,23d,“IT”,30d,30d,60d},
新对象[]{“Dave”,30d,“Sales”,50d,6d,60d}
};
XSSFRow行;
XSSFCell细胞;
for(int r=0;r
是否忘记关闭工作簿实例(wb.close()
)?您的FileOutputStream
已自动关闭,但工作簿不会关闭。@deHaar try with resources将处理关闭部分,但仍尝试关闭它。我写这篇文章的原因是我自己使用ApachePOI创建不可读工作簿的经验。我最终没有在资源中使用try
,原因有几点:try
with resources不flush()
FileOutputStream
。我总是使用常规的