简体   繁体   English

Java Apache Poi编写Excel

[英]Java Apache Poi Write Excel

I working in an application in Java to write to an excel. 我在Java中的应用程序中工作以写入Excel。 I am using apache poi libraries. 我正在使用apache poi库。 I have a requirement to create pivot table. 我需要创建数据透视表。 I am able to create pivot table and sum the columns using below code. 我能够使用以下代码创建数据透视表并汇总各列。

CellReference topLeft = new CellReference(0, 0);
CellReference bottomRight = new CellReference(10, 3);
AreaReference aref = new AreaReference(topLeft, bottomRight);
CellReference pos = new CellReference(0, 0);
XSSFSheet pivotSheet = workbook.createSheet("PivotSheet");
XSSFPivotTable pivotTable = pivotSheet.createPivotTable(aref,pos,dataSheet)
pivotOrgWiseSheet.setDisplayGridlines(true);
pivotTable.addRowLabel(0);
pivotTable.addRowLabel(1);
pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 2, "Sum of column3");
pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 3, "Sum of column4");

But the above code generate excel like 但是上面的代码生成像 在此处输入图片说明

But I am not sure why the keyword "values" comes in 2nd column header and also is it possible to change the value "Row Label" to custom text like "Category" 但是我不确定为什么关键字“ values”会出现在第二列标题中,并且也可能将值“ Row Label”更改为自定义文本,例如“ Category”

I want it something like below. 我想要类似下面的内容。

在此处输入图片说明

I am not sure how to remove the keyword "Values", but I guess to change the header to custom string, we have to get the value and set it out ? 我不确定如何删除关键字“ Values”,但是我想将标题更改为自定义字符串,我们必须获取值并将其设置为?

In Excel there is a setting Field Headers on the Analyze or Options tab, in the Show group. Excel ,“ Show组的“ Analyze或“ Options卡上有一个设置的“ Field Headers ”。 This switches between showing and hiding field headers. 这将在显示和隐藏字段标题之间切换。

See Change the layout of columns, rows, and subtotals . 请参阅更改列,行和小计的布局

The corresponding setting in org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotTableDefinition is setShowHeaders . org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotTableDefinition的相应设置为setShowHeaders

So 所以

...
pivotTable.getCTPivotTableDefinition().setShowHeaders(false);
...

should hiding field headers in your pivot table. 应该在数据透视表中隐藏字段标题。

But your picture of the wanted result looks more as if the data headers are visible but the RowHeaderCaption was changed and first row containing the DataCaption is hidden. 但是,所需结果的图片看起来更像是数据头可见,但RowHeaderCaption更改了,而包含DataCaption第一行被隐藏了。 That would be: 那将是:

...
//pivotTable.getCTPivotTableDefinition().setShowHeaders(false);
pivotTable.getCTPivotTableDefinition().setRowHeaderCaption("Category");
pivotTable.getCTPivotTableDefinition().setDataCaption("Changed Data Caption");
CellUtil.getRow(pos.getRow(), pivotSheet).setZeroHeight(true);
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM