Java (Apache POI) How to stretch XWPFTable row across whole page - java

I have a simple XWPFTable I made using Apache POI for docx, but if the text of the cell is short the cell/row resizes to fit around the text. How do I set it so the table/rows stay stretched from left to right of the whole page no matter the length of the text? Thanks.
Here's the table part of the code if It helps:
XWPFTable header = document.createTable(1, 3);
header.getRow(0).getCell(0).setText("LCode");
header.getRow(0).getCell(1).setText("QTY");
header.getRow(0).getCell(2).setText("Description/Justification");
XWPFTable table = document.createTable(LCodes.size(), 3);
int x = 0;
for (Map.Entry entry : new TreeMap<Integer, List<String>>(LCodes).entrySet()) {
Object LCode = entry.getKey();
table.getRow(x).getCell(0).setText("L" + LCode);
table.getRow(x).getCell(1).setText(LCodes.get(LCode).get(2));
XWPFParagraph para = table.getRow(x).getCell(2).getParagraphs().get(0);
for (int i = 0; i < 2; i++) {
if (i == 1 && LCodes.get(LCode).get(i).trim().equals("")) {
continue;
}
XWPFRun leading = para.createRun();
leading.setItalic(true);
if (i == 0) {
leading.setText("Description: ");
} else {
leading.setText("Justification: ");
}
XWPFRun trailing = para.createRun();
trailing.setText(LCodes.get(LCode).get(i));
if (i == 0 && !(LCodes.get(LCode).get(i).trim().equals(""))) {
trailing.addBreak();
}
}
x++;
}

To stretch width of xwpf table you need to perform following.
1. Create table in sample xwpf document.
2. Download the same document as zip and extract document.xml file.
3. Find
Another solution: If you dont want to go from all these and your table borders are hidden. You can add below XWPFparagraph in first column of your table and this will do the trick.
//add this para in first column to get table width, 84pts total
private XWPFParagraph getFirstColumnText(){
XWPFParagraph para=new XWPFDocument().createParagraph();
XWPFRun run=para.createRun();
run.setColor("ffffff");
run.setText("...................................................................................");
return para;
}

Related

How to insert a large PDF table into PDF document that doesn't fit on one page using Itext?

I make a PDF table with three columns and the number of rows is determined by the arrays of data that I get from a device. These can vary anywhere from 1 to 200+ rows.
When the data that I get is less than how many rows can fit on a page, everything works fine, but when I get a lot of data, 40+ rows, I get the Document exception - infinite loop.
Here is the method where I make the table:
private static PdfPTable createTableSerial(String[] serialOcr, ArrayList<java.awt.Image> serialImage)
throws BadElementException {
PdfPTable table = new PdfPTable(3);
// t.setBorderColor(BaseColor.GRAY);
// t.setPadding(4);
// t.setSpacing(4);
// t.setBorderWidth(1);
PdfPCell c1 = new PdfPCell(new Phrase("Apoen"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Serijski broj"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Slika serijskog broja"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
table.setHeaderRows(serialImage.size() - 1);
try {
int i = 0;
int j = 0;
while (j < serialImage.size()) {
table.addCell(serialOcr[i]);
table.addCell(serialOcr[i + 1]);
table.addCell(Image.getInstance(serialImage.get(j), null));
i += 2;
j++;
}
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
} catch (IOException e) {
throw new RuntimeException(e);
}
return table;
}
And I call it later like this:
document.add(createTableSerial(serialOcr, serialImage));
I tried using the method:
table.splitLateRows(false);
But it didn't work.
A version of Itext is itextpdf-5.5.13.2.jar
How can I split the table if it's bigger than one page?
Can I check how much free space there is on a pdf page?
Thanks in advance.
I tried a lot of things, but the one below is the only way I got it to work.
Maybe it could be easier with a newer version of IText, but with version 5.5 that I used this is the only way I could find.
PdfPTable largeTable = createTableSerial(serialOcr, serialImage);
List<PdfPRow> rows = largeTable.getRows();
int rowsPerTable = 20;
int currentRow = 0;
while(currentRow < rows.size()){
PdfPTable smallTable = new PdfPTable(largeTable.getNumberOfColumns());
smallTable.setWidthPercentage(100);
for (int i = currentRow; i < currentRow + rowsPerTable; i++) {
if (i >= rows.size()) {
break;
}
PdfPCell[] cells = rows.get(i).getCells();
for (PdfPCell cell : cells) {
smallTable.addCell(cell);
}
}
document.add(smallTable);
currentRow += rowsPerTable;
}
I first call the method that I posted in my question and create one large table.
After this I break the large table into multiple small tables and add them to the Pdf document one by one.
You can adjust the int rowsPerTable = 20; value to define on how many rows will the table break.

How can I duplicate a table in word with apache poi? [duplicate]

I have a table in the docx template.
Depending on the number of objects, I have to duplicate the table as many times as I have objects. Duplicate tables must be after the table from the template.
I have several tables in the template that should behave like this.
XmlCursor take the place of the first table from the template and put the next one there. I want to insert the next table after the previous one, which I added myself, but xmlcursor does not return the table item I added, but returns "STARTDOC"
XmlCursor cursor = docx.getTables().get(pointer).getCTTbl().newCursor();
cursor.toEndToken();
while (cursor.toNextToken() != XmlCursor.TokenType.START) ;
XWPFParagraph newParagraph = docx.insertNewParagraph(cursor);
newParagraph.createRun().setText("", 0);
cursor.toParent();
cursor.toEndToken();
while (cursor.toNextToken() != XmlCursor.TokenType.START) ;
docx.insertNewTbl(cursor);
CTTbl ctTbl = CTTbl.Factory.newInstance();
ctTbl.set(docx.getTables().get(numberTableFromTemplate).getCTTbl());
XWPFTable tableCopy = new XWPFTable(ctTbl, docx);
docx.setTable(index + 1, tableCopy);
Not clear what you are aiming for with the cursor.toParent();. And I also cannot reproduce the issue having only your small code snippet. But having a complete working example may possible help you.
Assuming we have following template:
Then following code:
import java.io.FileOutputStream;
import java.io.FileInputStream;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.XmlCursor;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl;
public class WordCopyTableAfterTable {
static XmlCursor setCursorToNextStartToken(XmlObject object) {
XmlCursor cursor = object.newCursor();
cursor.toEndToken(); //Now we are at end of the XmlObject.
//There always must be a next start token.
while(cursor.hasNextToken() && cursor.toNextToken() != org.apache.xmlbeans.XmlCursor.TokenType.START);
//Now we are at the next start token and can insert new things here.
return cursor;
}
static void removeCellValues(XWPFTableCell cell) {
for (XWPFParagraph paragraph : cell.getParagraphs()) {
for (int i = paragraph.getRuns().size()-1; i >= 0; i--) {
paragraph.removeRun(i);
}
}
}
public static void main(String[] args) throws Exception {
//The data. Each row a new table.
String[][] data= new String[][] {
new String[] {"John Doe", "5/23/2019", "1234.56"},
new String[] {"Jane Doe", "12/2/2019", "34.56"},
new String[] {"Marie Template", "9/20/2019", "4.56"},
new String[] {"Hans Template", "10/2/2019", "4567.89"}
};
String value;
XWPFDocument document = new XWPFDocument(new FileInputStream("WordTemplate.docx"));
XWPFTable tableTemplate;
CTTbl cTTblTemplate;
XWPFTable tableCopy;
XWPFTable table;
XWPFTableRow row;
XWPFTableCell cell;
XmlCursor cursor;
XWPFParagraph paragraph;
XWPFRun run;
//get first table (the template)
tableTemplate = document.getTableArray(0);
cTTblTemplate = tableTemplate.getCTTbl();
cursor = setCursorToNextStartToken(cTTblTemplate);
//fill in first data in first table (the template)
for (int c = 0; c < data[0].length; c++) {
value = data[0][c];
row = tableTemplate.getRow(1);
cell = row.getCell(c);
removeCellValues(cell);
cell.setText(value);
}
paragraph = document.insertNewParagraph(cursor); //insert new empty paragraph
cursor = setCursorToNextStartToken(paragraph.getCTP());
//fill in next data, each data row in one table
for (int t = 1; t < data.length; t++) {
table = document.insertNewTbl(cursor); //insert new empty table at position t
cursor = setCursorToNextStartToken(table.getCTTbl());
tableCopy = new XWPFTable((CTTbl)cTTblTemplate.copy(), document); //copy the template table
//fill in data in tableCopy
for (int c = 0; c < data[t].length; c++) {
value = data[t][c];
row = tableCopy.getRow(1);
cell = row.getCell(c);
removeCellValues(cell);
cell.setText(value);
}
document.setTable(t, tableCopy); //set tableCopy at position t instead of table
paragraph = document.insertNewParagraph(cursor); //insert new empty paragraph
cursor = setCursorToNextStartToken(paragraph.getCTP());
}
paragraph = document.insertNewParagraph(cursor);
run = paragraph.createRun();
run.setText("Inserted new text below last table.");
cursor = setCursorToNextStartToken(paragraph.getCTP());
FileOutputStream out = new FileOutputStream("WordResult.docx");
document.write(out);
out.close();
document.close();
}
}
leads to following result:
Is that about what you wanted to achieve?
Please note how I insert the additional tables.
Using table = document.insertNewTbl(cursor); a new empty table is inserted at position t. This table is placed into the document body. So this table must be taken for adjusting the cursor.
Then tableCopy = new XWPFTable((CTTbl)cTTblTemplate.copy(), document); copys the template table. Then this copy is filled with data. And then it is set into the document at position t using document.setTable(t, tableCopy);.
Unfortunately apache poi is incomplete here. XWPFDocument.setTable only sets the internally ArrayLists but not the underlying XML. XWPFDocument.insertNewTbl sets the underlying XML but only using an empty table. So we must do it that ugly complicated way.

XSSFTable setDataRowCount overwrites totals row [duplicate]

I've got an table in excel with formulae I would like to add data to.
My motivation for this is the fact that tables in excel can dynamically expand to the range of data you add to them, meaning that the formula rows automatically keep up with the amount of data rows.
I'm however having a hard time finding out if this is possible using apache-POI.
One thing I was going to try (see code below) was to expand the AreaReference of the table to cover the data, however both AreaReference(CR,CR2); (as used in this example) and AreaReference(CR,CR2, SpreadsheetVersion.EXCEL2007) (seen in the apache docs) give "constructor is undefined".
No idea what is causing that constructor error as I do have org.apache.poi.ss.util imported.
The other option on the apache docs AreaReference(java.lang.String reference) lets me compile and run but instead gives a "NoSuchMethod" error.
List<XSSFTable> tableList = spreadSheet.getTables();
CellReference CR = new CellReference(0, 0);
CellReference CR2 = new CellReference(5, 2);
AreaReference my_data_range = new AreaReference(CR,CR2);
tableList.get(0).setArea(my_data_range);
Any help will be appreciated.
The main problem using apache poi until now is that it is not ready to be used without having detailed knowledge about Microsoft Office as such and about the storage of Microsoft Office files. There are many things only half way ready and there are regressions often in new versions (bugs occur again which were solved already).
So your requirement: "Expanding an existing table in Excel using Apache POI" is not possible only simply using apache poi. One must know that Office Open XML files *.xlsx are simply ZIP archives which can be unzipped. And after unzipping we find /xl/tables/table1.xml for storage of the table. This XML we can analyzing and comparing it with XML which was created using Excel's GUI. So we can find problems which results from shortcomings of apache poi. Same is with the sheet's XML in /xl/tables/sheet1.xml.
Also we need to know that apache poi builds on the low level classes of ooxml-schemas. Partially we need using those classes because of the halfway readiness of apache poi. In the following example we need ooxml-schemas-1.4.jar additionally because apache poi's poi-ooxml-schemas-4.0.0.jar has not included org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableFormula until now. Unfortunately there is no documentation about ooxml-schemas public available. So we need downloading the sources and doing javadoc our own.
The following example works for me using apache poi 4.0.0. If you get problems while compiling or running, the reason might be that multiple different versions of apache poi jars are in class path while compile time and/or run time. Do not mix different apache poi versions. Also, as said already, my code needs the full jar of all of the schemas ooxml-schemas-1.4.jar.
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.ss.SpreadsheetVersion;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableColumn;
class ExcelExpandingTable {
static void addRowToTable(XSSFTable table) {
int lastTableRow = table.getEndCellReference().getRow();
int totalsRowCount = table.getTotalsRowCount();
int lastTableDataRow = lastTableRow - totalsRowCount;
// we will add one row in table data
lastTableRow++;
lastTableDataRow++;
// new table area plus one row
AreaReference newTableArea = new AreaReference(
table.getStartCellReference(),
new CellReference(
lastTableRow,
table.getEndCellReference().getCol()
),
SpreadsheetVersion.EXCEL2007
);
// new table data area plus one row
AreaReference newTableDataArea = new AreaReference(
table.getStartCellReference(),
new CellReference(
lastTableDataRow,
table.getEndCellReference().getCol()
),
SpreadsheetVersion.EXCEL2007
);
XSSFSheet sheet = table.getXSSFSheet();
if (totalsRowCount > 0) {
//if we have totals rows, shift totals rows down
sheet.shiftRows(lastTableDataRow, lastTableRow, 1);
// correcting bug that shiftRows does not adjusting references of the cells
// if row 3 is shifted down, then reference in the cells remain r="A3", r="B3", ...
// they must be adjusted to the new row thoug: r="A4", r="B4", ...
// apache poi 3.17 has done this properly but had have other bugs in shiftRows.
for (int r = lastTableDataRow; r < lastTableRow + 1; r++) {
XSSFRow row = sheet.getRow(r);
if (row != null) {
long rRef = row.getCTRow().getR();
for (Cell cell : row) {
String cRef = ((XSSFCell)cell).getCTCell().getR();
((XSSFCell)cell).getCTCell().setR(cRef.replaceAll("[0-9]", "") + rRef);
}
}
}
// end correcting bug
}
// if there are CalculatedColumnFormulas do filling them to the new row
XSSFRow row = sheet.getRow(lastTableDataRow); if (row == null) row = sheet.createRow(lastTableDataRow);
int firstTableCol = table.getStartCellReference().getCol();
for (CTTableColumn tableCol : table.getCTTable().getTableColumns().getTableColumnList()) {
if (tableCol.getCalculatedColumnFormula() != null) {
int id = (int)tableCol.getId();
String formula = tableCol.getCalculatedColumnFormula().getStringValue();
XSSFCell cell = row.getCell(firstTableCol + id - 1); if (cell == null) cell = row.createCell(firstTableCol + id - 1);
cell.setCellFormula(formula);
}
}
table.setArea(newTableArea);
// correcting bug that Autofilter includes possible TotalsRows after setArea new
// Autofilter must only contain data area
table.getCTTable().getAutoFilter().setRef(newTableDataArea.formatAsString());
// end correcting bug
table.updateReferences();
}
public static void main(String[] args) throws Exception {
try (Workbook workbook = WorkbookFactory.create(new FileInputStream("SAMPLE.xlsx"));
FileOutputStream out = new FileOutputStream("SAMPLE_NEW.xlsx")) {
XSSFSheet sheet = ((XSSFWorkbook)workbook).getSheetAt(0);
XSSFTable table = sheet.getTables().get(0);
addRowToTable(table);
workbook.write(out);
}
}
}
The above was 2018. Now we have 2022.
Using current apache poi 5.2.2 the code may be like follows:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.ss.SpreadsheetVersion;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableColumn;
class ExcelExpandingTable {
static XSSFRow addRowToTable(XSSFTable table) {
int lastTableRow = table.getEndCellReference().getRow();
int totalsRowCount = table.getTotalsRowCount();
int lastTableDataRow = lastTableRow - totalsRowCount;
int firstTableCol = table.getStartCellReference().getCol();
// we will add one row in table data
lastTableRow++;
lastTableDataRow++;
// new table area plus one row
AreaReference newTableArea = new AreaReference(
table.getStartCellReference(),
new CellReference(
lastTableRow,
table.getEndCellReference().getCol()
),
SpreadsheetVersion.EXCEL2007
);
XSSFSheet sheet = table.getXSSFSheet();
if (totalsRowCount > 0) {
//if we have totals rows, shift totals rows down
sheet.shiftRows(lastTableDataRow, lastTableRow, 1);
//correct all sheet table-reference-formulas which probably got damaged after shift rows
for (CTTableColumn tableCol : table.getCTTable().getTableColumns().getTableColumnList()) {
if (tableCol.getCalculatedColumnFormula() != null) {
int id = (int)tableCol.getId();
String formula = tableCol.getCalculatedColumnFormula().getStringValue();
int rFirst = table.getStartCellReference().getRow() + table.getHeaderRowCount();
int rLast = table.getEndCellReference().getRow() - table.getTotalsRowCount();
int c = table.getStartCellReference().getCol() + id - 1;
sheet.getWorkbook().setCellFormulaValidation(false);
for (int r = rFirst; r <= rLast; r++) {
XSSFRow row = sheet.getRow(r); if (row == null) row = sheet.createRow(r);
XSSFCell cell = row.getCell(c); if (cell == null) cell = row.createCell(c);
cell.setCellFormula(formula);
}
}
}
}
// if there are CalculatedColumnFormulas do filling them to the new row
XSSFRow row = sheet.getRow(lastTableDataRow); if (row == null) row = sheet.createRow(lastTableDataRow);
for (CTTableColumn tableCol : table.getCTTable().getTableColumns().getTableColumnList()) {
if (tableCol.getCalculatedColumnFormula() != null) {
int id = (int)tableCol.getId();
String formula = tableCol.getCalculatedColumnFormula().getStringValue();
XSSFCell cell = row.getCell(firstTableCol + id - 1); if (cell == null) cell = row.createCell(firstTableCol + id - 1);
cell.getSheet().getWorkbook().setCellFormulaValidation(false); // see https://bz.apache.org/bugzilla/show_bug.cgi?id=66039
cell.setCellFormula(formula);
}
}
// copy cell styles to the new row from the row above
row = sheet.getRow(lastTableDataRow); if (row == null) row = sheet.createRow(lastTableDataRow);
XSSFRow rowAbove = sheet.getRow(lastTableDataRow - 1); if (row == null) row = sheet.createRow(lastTableDataRow - 1);
for (CTTableColumn tableCol : table.getCTTable().getTableColumns().getTableColumnList()) {
int id = (int)tableCol.getId();
XSSFCell cellAbove = rowAbove.getCell(firstTableCol + id - 1);
if (cellAbove != null) {
XSSFCellStyle styleAbove = cellAbove.getCellStyle();
XSSFCell cell = row.getCell(firstTableCol + id - 1); if (cell == null) cell = row.createCell(firstTableCol + id - 1);
cell.setCellStyle(styleAbove);
}
}
// set new table area
table.setArea(newTableArea);
// update table references
table.updateReferences();
return sheet.getRow(lastTableDataRow);
}
public static void main(String[] args) throws Exception {
try (Workbook workbook = WorkbookFactory.create(new FileInputStream("SAMPLE.xlsx"));
FileOutputStream out = new FileOutputStream("SAMPLE_NEW.xlsx")) {
XSSFSheet sheet = ((XSSFWorkbook)workbook).getSheetAt(0);
XSSFTable table = sheet.getTables().get(0);
XSSFRow row = addRowToTable(table);
workbook.write(out);
}
}
}
According to FAQ, this code needs poi-ooxml-full-5.2.2.jar instead of ooxml-schemas-1.4.jar now for run using apache poi 5.2.2.
Some bugs are fixed. But there is one new bug when using XSSFCell.setCellFormula when formula contains table references. But XSSFWorkbook.setCellFormulaValidation(false) avoids this.

Using XWPFParagraph and XWPFRun, how to make the lines printing on the same. See the description please

I'm generating a .docx file from Java using Apache POI.
I'm having a table that has columns like..
table without any entry
I'm writing the content inside second row using following code.
String itemNames[] = {“Item 1”, “Item Name 2”, "Item 3"};
for(int i=0; i<3; i++) {
//getRow(1) represents second row of the table
//printing sr. no
paragraph = table.getRow(1).getCell(0).addParagraph();
paragraph.setAlignment(ParagraphAlignment.CENTER);
paragraph.setVerticalAlignment(TextAlignment.CENTER);
run = paragraph.createRun();
run.setText(i+1);
//printing item names
paragraph = table.getRow(1).getCell(1).addParagraph();
paragraph.setAlignment(ParagraphAlignment.CENTER);
paragraph.setVerticalAlignment(TextAlignment.CENTER);
run = paragraph.createRun();
run.setText(itemNames[i]);
//printing qty
paragraph = table.getRow(1).getCell(2).addParagraph();
paragraph.setAlignment(ParagraphAlignment.CENTER);
paragraph.setVerticalAlignment(TextAlignment.CENTER);
run = paragraph.createRun();
run.setText(1 + (i*10));
}
That is generating the output like below.
Error picture
In this, as you can see, the item name for row 2 can't be written in 1 line as cell width is smaller than the content. So, there's word wrap set so that line completes writing in 2 lines. However, rest of the content take only 1 line.
So when the code is printing third entry, it is creating a new paragraph in sr no, item name and qty and writing the values. But, as you can see in the image, the output is not as it should be.
I tried to get number of lines in paragraph and in run also but I could not get the actual number and as the item name is bigger, I want to add breaks to other columns to save it in proper form. But how to find the line numbers for every run for the cell 2 in row 2?
What I would do is writing the content of row 2 of the table into the already present row and then for each further content row, creating a new XWPFTableRow using XWPFTable.createRow.
Example:
First table in WordTableExample.docx:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;
public class WordInsertTableRows {
public static void main(String[] args) throws Exception {
XWPFDocument doc = new XWPFDocument(new FileInputStream("WordTableExample.docx"));
XWPFTable table = doc.getTableArray(0);
XWPFTableRow row;
XWPFParagraph paragraph;
XWPFRun run;
String itemNames[] = {"Item 1", "Item Name 2", "Item 3"};
for(int i=0; i<itemNames.length; i++) {
row = table.getRow(1+i); //getRow(1) represents second row of the table
if (row == null) row = table.createRow(); //if there is not a row already, then create one
//printing sr. no
paragraph = row.getCell(0).getParagraphArray(0);
if (paragraph == null) paragraph = row.getCell(0).addParagraph();
paragraph.setAlignment(ParagraphAlignment.CENTER);
//paragraph.setVerticalAlignment(TextAlignment.CENTER); //this sets valign for the paragraph
row.getCell(0).setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); //I suspect you wants set valign for the cell
run = paragraph.createRun();
run.setText(""+(i+1));
//printing item names
paragraph = row.getCell(1).getParagraphArray(0);
if (paragraph == null) paragraph = row.getCell(1).addParagraph();
paragraph.setAlignment(ParagraphAlignment.CENTER);
//paragraph.setVerticalAlignment(TextAlignment.CENTER);
row.getCell(1).setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
run = paragraph.createRun();
run.setText(itemNames[i]);
//printing qty
paragraph = row.getCell(2).getParagraphArray(0);
if (paragraph == null) paragraph = row.getCell(2).addParagraph();
//paragraph.setVerticalAlignment(TextAlignment.CENTER);
row.getCell(2).setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
run = paragraph.createRun();
run.setText(""+(1 + (i*10)));
}
doc.write(new FileOutputStream("WordTableExampleNew.docx"));
doc.close();
}
}

Cell values not getting set for newly added rows : using apache poi

I have a table in a ppt slide. Data to the table will be read from an ArrayList (Each object in the ArrayList will contain one row data) of String[].
If the number of rows in the table is less than the size of the ArrayList, new rows will be added to match the size of the ArrayList.
Problem here is data is getting set for already existing rows but not for the newly added rows. Please find the code snippet below.
Any help/suggestion is much appreciated. Thanks in advance.
XSLFTable table = (XSLFTable) shape;
int noOfDataRows=table.getNumberOfRows()-1;
if(noOfDataRows<ap.size()) {
for(int rws=0;rws<(ap.size()- noOfDataRows);rws++) {
System.out.println(" Adding row");
table.addRow();
}
}
List<XSLFTableRow> rows = table.getRows();
for (int i = 0; i < ap.size(); i++) {
String[] awaitprop={'1','2','3','4','5','6','7','8'};
XSLFTableRow row=rows.get(i+1);
List<XSLFTableCell> cells=row.getCells();
for(int j=0;j<cells.size();j++) {
XSLFTableCell cell=cells.get(j);
cell.clearText();
XSLFTextParagraph paragraph=cell.addNewTextParagraph();
paragraph.setTextAlign(TextAlign.CENTER);
XSLFTextRun textRun=paragraph.addNewTextRun();
textRun.setFontFamily("Calibri");
textRun.setFontSize(11);
textRun.setText(awaitprop[j]);
}
}
With reference to following tutorial, at first you should create cell(s) in the new row, I guess. Then you can put a content there.
XSLFTableRow headerRow = table.addRow();
for(int i = 0; i < 3; i++) {
XSLFTableCell th = headerRow.addCell();
XSLFTextParagraph p = th.addNewTextParagraph();
XSLFTextRun r = p.addNewTextRun();
r.setText("Text");
}
I hope it helps!

Categories

Resources