Java Excel Pivot Table Field Conditional Formatting - java

Please, could you advise, how to set up a Conditional formatting related to the MS Excel Pivot Table Data Field (not to the Excel sheet cell !). The Excel pivot table is created via Java Apache Poi. I need a pure Java solution either via the Apache Poi library or via Spire.XLS or Aspose library. I prefer open source solution but if there is no other option I would welcome paid library if the solution works well. I failed searching this via Google Worldwide. Thank you very much. Miroslav

Aspose.Cells for Java can serve your needs. You may add conditional formattings to pivot table fields (row, column, data, etc.).
There are relevant APIs (method overloads, etc.) for the purpose:
PivotFormatCondition.addDataAreaCondition(string fieldName) method
which adds PivotTable conditional format limit in the data fields.
PivotFormatCondition.addDataAreaCondition(PivotField dataField)
method which adds PivotTable conditional format limit in the data
fields.
PivotFormatCondition.addRowAreaCondition(string fieldName) method
which adds PivotTable conditional format range limit in the row
fields.
PivotFormatCondition.addRowAreaCondition(PivotField rowField) method
which adds PivotTable conditional format range limit in the row
fields.
PivotFormatCondition.addColumnAreaCondition(string fieldName) method
which adds PivotTable conditional format range limit in the column
fields.
PivotFormatCondition.addColumnAreaCondition(PivotField columnField)
method which adds PivotTable conditional format range limit in the
column fields.
PivotFormatCondition.setConditionalAreas() method which sets
conditional areas of PivotFormatCondition object.
e.g.
Sample code:
String filePath = "........";
Workbook workbook = new Workbook(filePath + "Book1.xlsx");
//Get the first pivot table in the first worksheet.
PivotTable pivot = workbook.getWorksheets().get(0).getPivotTables().get(0);
PivotFormatConditionCollection pfcs = pivot.getPivotFormatConditions();
//clear all the current conditional formats (if required).
pfcs.clear();
workbook.getWorksheets().get(0).getConditionalFormattings().clear();
//Add new conditional formatting
int pIndex = pfcs.add();
PivotFormatCondition pfc = pfcs.get(pIndex);
pfc.setScopeType(PivotConditionFormatScopeType.FIELD);
//Sample code 1:
pfc.addDataAreaCondition("myDataField1");
pfc.addRowAreaCondition("myRowField");
//Or
//Sample code 2:
// pfc.addDataAreaCondition(pivot.DataFields[2]);
// pfc.addRowAreaCondition(pivot.RowFields[0]);
pfc.setConditionalAreas();
FormatConditionCollection fcc = pfc.getFormatConditions();
int idx = fcc.addCondition(FormatConditionType.CELL_VALUE);
FormatCondition fc = fcc.get(idx);
fc.setFormula1("0.4");
fc.setOperator(OperatorType.GREATER_OR_EQUAL);
fc.getStyle().setBackgroundColor(com.aspose.cells.Color.getRed());
workbook.save(filePath + "out.xlsx");
workbook.save(filePath + "out.pdf");
You may also post your queries or comments in other forums.
PS. I am working as Support developer/ Evangelist at Aspose.

Related

Filter by Value rather than by label in an XSSFPivotTable with Apache POI and Java

I am trying to add an AutoFilter to a pivot table column which filters the data by value instead of by caption. This is my code on how I am trying to do it:
pivotTable2.addColumnLabel(DataConsolidateFunction.SUM, 29);
pivotTable2.addRowLabel(29);
pivotTable2.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(29).setDataField(true);
-- Skipping making table lines of code --
org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotFilters filters =
org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotFilters.Factory.newInstance();
org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotFilter filter = filters.addNewFilter();
filter.setId(0);
filter.setFld(29);
filter.setType(org.openxmlformats.schemas.spreadsheetml.x2006.main.STPivotFilterType.VALUE_LESS_THAN);
filter.setStringValue1("0");
CTFilterColumn myCol = filter.addNewAutoFilter().addNewFilterColumn();
CTCustomFilters myFilter2= myCol.addNewCustomFilters();
CTCustomFilter custFilt = myFilter2.addNewCustomFilter();
custFilt.setOperator(STFilterOperator.LESS_THAN);
custFilt.setVal("0");
// filter.addNewAutoFilter().addNewFilterColumn().addNewCustomFilters().addNewCustomFilter().setVal("0");
filter.getAutoFilter().setRef("A1");
filter.getAutoFilter().getFilterColumnArray(0).setColId(0);
//set filters to pivot table definition
pivotTable2.getCTPivotTableDefinition().setFilters(filters);
However, whenever I run this code, the data filter does not appear for the pivot table and instead prints the pivot table as normal. If I try CAPTION_LESS_THAN, it autofilters for the label filter rather than the value filter. It may have to do with adding a data filter, but I am not sure where to add it. Can you please help me out on this.

How to refresh and then read the data from Pivot Table using Apache POI?

I wanna dynamically supply some source data for Pivot Table using Apache POI which is not a problem at all.
When it comes to refreshing the Pivot Table with new data it seems like POI doesn't have the ability to refresh it in runtime and then read the generated data produced by Pivot Table, is that possible to achieve by Apache POI?
XSSFSheet sheet = wb.createSheet("Test SHEET");
XSSFPivotTable pivotTable = sheet.createPivotTable(new AreaReference("'Test 1'!$A$1:$S$1048575", SpreadsheetVersion.EXCEL2007), new CellReference("A1"));
pivotTable.addRowLabel(9); // name
//Sum up the second column
pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 6); // weight
// NEED TO REFRESH AND THEN READ THE SECOND COLUMN WHICH IS ABOVE

Java Apache POI (Excel) Convert Data in Sheet to Table

I'm trying to put together a report for a customer using Apache POI and I was getting on well with it, but the last major step is taking the existing data and putting it in table objects. I've been learning as I go but this last part escapes me, and the file is generated without any errors in Eclipse but Windows complains about it being corrupt so I don't get any useful messages to help me figure it out. At this point I'm not entirely sure if I'm even doing it in the correct order, so here's the situation:
I need to pull down data from a SQL database; process it and (depending on one piece of the data) put it in a particular tab in the spreadsheet (all working fine).
Each of those tabs contains essentially the same table with the same columns (16) but differing numbers of rows.
I need a grand totals row at the bottom which can update dynamically depending on filter options, the easiest option seemed to be putting the data into Table objects and in previous Excel macro-based versions of this report that worked ok, but building the thing in Java is a lot cleaner for various reasons.
The current iteration of the code generates the sheet fine and leaves me with the data in the correct rows and columns, I just need to know how I can take that data and put it into Table objects and the documentation hasn't been much help there. I'm not actually sure if I should be generating the table objects at the end when I have all the data or if I should be generating them first and having the code populate the table instead of the base sheet (and I don't know how either of those is best accomplished). I've found some example code for creating and populating a table with basic integers and I tried to modify it to suit, but I'm not having much luck. If someone could point out what I'm doing wrong here I'd appreciate it!
for (int sheetIndex = 1; sheetIndex < wb.getNumberOfSheets(); sheetIndex++)
{
XSSFSheet current = wb.getSheetAt(sheetIndex);
//Create
XSSFTable table = current.createTable();
table.setDisplayName(current.getSheetName());
CTTable cttable = table.getCTTable();
DataFormatter formatter = new DataFormatter();
//Style configurations
//CTTableStyleInfo style = cttable.addNewTableStyleInfo(); //Doesn't seem to work?
//style.setName("TableStyleMedium2");
//style.setShowColumnStripes(false);
//style.setShowRowStripes(true);
//Set which area the table should be placed in
CellReference lastCell = new CellReference(current.getLastRowNum(),current.getRow(0).getLastCellNum());
AreaReference reference = new AreaReference(new CellReference(0, 0),lastCell);
cttable.setRef(reference.formatAsString());
cttable.setId(1);
cttable.setName("Test");
cttable.setTotalsRowCount(1);
cttable.setTotalsRowShown(true);
CTTableColumns columns = cttable.addNewTableColumns();
columns.setCount(16);
CTTableColumn column;
XSSFRow row;
XSSFCell cell;
for(int i=0; i<16; i++) { //16 used for testing purposes
//Create column
column = columns.addNewTableColumn();
column.setName(formatter.formatCellValue(current.getRow(0).getCell(i)));
column.setId(i+1);
//Create row
row = current.createRow(i);
for(int j=0; j<4; j++) { //4 used for testing purposes
//Create cell
cell = row.createCell(j);
cell.setCellValue(formatter.formatCellValue(current.getRow(j).getCell(i)));
}
}
}

can we add multiple rows to existing table in word template using java

I have a Word template including a table (3 columns and one row). I want to add more rows to this table using any API in Java. Can I add additional rows to an existing table in Word 2010 template?
Use Java Apache POI found here https://poi.apache.org/ but this may be a bit tricky unless you are using excel.
Another option is the Aspose APIs found here http://www.aspose.com/
This code would add a row to an existing table
Document doc = new Document(MyDir + "document.docx");
// Retrieve the first table in the document.
Table table = (Table)doc.getChild(NodeType.TABLE, 0, true);
// Clone the last row in the table.
Row clonedRow = (Row)table.getLastRow().deepClone(true);
// Remove all content from the cloned row's cells. This makes the row ready for
// new content to be inserted into.
for (Cell cell: clonedRow.getCells())
{
cell.getFirstParagraph().getRuns().clear();
cell.getFirstParagraph().appendChild(new Run(doc,"hello text"));
}
// Add the row to the end of the table.
table.appendChild(clonedRow);
doc.save(MyDir + "Table.AddCloneRowToTable Out.doc");
Ref: http://www.aspose.com/community/forums/thread/648997/reg-adding-rows-dynamically-to-the-existing-table-in-the-document.aspx

How to create dependent drop downs in excel sheet generated using POI?

we have a function in our java based web application where user can download an excel sheet template from the web application. Fill their data in this template and then upload the same excel sheet.
The system then reads this excel file and save this data in the database.
Below is snapshot of template file with some sample data in it.
What I want is when users download template file (template file usually just has the headers, so users know which data goes in which column), excel sheet should have drop downs for Division, Product, secondary product , Region and country. So that users do not enter any invalid values in those columns.
As well, products varies according to divisions and secondary product varies according to products. Its more like dependent drop downs.
Basically I will need to create the excel sheet using Apache POI in which users will chose values from the drop dowsn instead of typing it themselevs.
Even though we do have server side validation where we check if the values entered by users are valid or not.
The reason we wnat to do this is that e.g. some users might enter country as US, some as USA and some as United states.
The same thing goes for products etc. user may enter product as GFFX or GFFX Structuring or gffx etc.
Is it possible to do this in excel sheet using POI? If not what are the other possible solutions or wasy to make sure users know what they have to enter in each columns?
EDIT 1 :
I could created the drop downs but is it possible to created the dependent drop downs?
I was about to suggest AurA's solution but it looks like you'll have to build the validation list at run-time indeed.
You should have a look at the POI Quick Guide, it seems they have exactly what you need:
hssf.usermodel (binary .xls format)
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Data Validation");
CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0);
DVConstraint dvConstraint = DVConstraint.createExplicitListConstraint(new String[]{"10", "20", "30"});
DataValidation dataValidation = new HSSFDataValidation(addressList, dvConstraint);
dataValidation.setSuppressDropDownArrow(false);
sheet.addValidationData(dataValidation);
xssf.usermodel (.xlsx format)
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Data Validation");
XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(sheet);
XSSFDataValidationConstraint dvConstraint = (XSSFDataValidationConstraint)
dvHelper.createExplicitListConstraint(new String[]{"11", "21", "31"});
CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0);
XSSFDataValidation validation = (XSSFDataValidation)dvHelper.createValidation(
dvConstraint, addressList);
validation.setShowErrorBox(true);
sheet.addValidationData(validation);
You can get drop-down list (after clicking right mouse button) in case you've added (using POI) suggestions to the rows upper the first row that is visible to the user and should be filled (thus the rows beneath the header contain suggestions and are hgidden).
You won't get (AFAIK) category dependancy with POI or even pure excel (without VBA) drop-down list (that holds suggestions on the basis of values entered earlier).
What you can do, is to use POI to fill helper sheet with appropriate raw data and use VBA to dynamically generate drop-downs that would allow to pick a value from a list.

Categories

Resources