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)));
}
}
}
Related
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.
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
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
Dear all member here!!
I got a problem that need to ask your help. I already have an excel file (sample.xlsx). I need to use java code for appending my old data.
Here is my specifications:
My old data is in column A, 100 rows for example.
Need to write other data (50 rows) in different column, column B for example.
Appending data is also start from first row as the old data.
Is it possible to do that in POI?
Here is what you need to do.
XSSFSheet sheet = workbook.getSheet("sample");
for(int i=0; i<numberOfRowsToWriteDataIn; i++) {
XSSFRow row = sheet.getRow(i);
row.createCell(5).setCellValue("Creation Date: "+ new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
}
Hope that helps.
I recently downgraded my code to use JDK 1.4 and Apache 3.2(Final).
Note: For those who are asking why i chose to downgrade. I need to deploy it on servers that use those settings.
Before downgrading everything, my code is working just fine and encountered no errors. I ran the same sample as I used with my previous code and encountered this error:
java.lang.IllegalStateException: Cannot get a numeric value from a text formula cell
at org.apache.poi.hssf.usermodel.HSSFCell.typeMismatch(HSSFCell.java:620)
at org.apache.poi.hssf.usermodel.HSSFCell.checkFormulaCachedValueType(HSSFCell.java:625)
at org.apache.poi.hssf.usermodel.HSSFCell.getNumericCellValue(HSSFCell.java:650)
at org.apache.poi.hssf.usermodel.HSSFCell.setCellType(HSSFCell.java:308)
at org.apache.poi.hssf.usermodel.HSSFCell.setCellType(HSSFCell.java:274)
at com.Generate.Excel.Actions.ProtonMonthlyStatActions.generatePRDXSheet(ProtonMonthlyStatActions.java:292)
The error points to this piece of code in the else part surrounded by double asterisk:
for (int x =0 ; x<dataList.getDHourList().size(); x++){ //for loop copying throughput data to excel file
row = prdX.getRow(x+2);
//checks if 3rd row in excel contains data (x+2) where x = 0 since excel is zero based
if (isRowEmpty(prdX.getRow(x+2))== true){
row = prdX.createRow(x+2); //creates row
//for Hour Computation
cell = row.createCell(colVal[2]);//creates column for Hour Computation using the formula specified
cell.setCellType(HSSFCell.CELL_TYPE_FORMULA);
cell.setCellFormula("MID("+formulaCell[0]+(x+3)+",12,2)");//fixed formula taken from Excel Template
}
//If row is not empty each cells in every row is iterated and processed
else {
//for Hour Computation
cell = row.getCell(colVal[2], HSSFRow.CREATE_NULL_AS_BLANK);
**cell.setCellType(HSSFCell.CELL_TYPE_FORMULA);**
cell.setCellFormula("MID("+formulaCell[0]+(x+3)+",12,2)");
}
}
I think that this error is referring to text values in the cell.setCellFormula part... but how else would I specify a formula in Apache 3.2. Any suggestions for this?