Issue
I'm trying to put every single row from JTable (xlTab, 3 columns)
in its own page in XWPFDocument
(If rows=10, then pages=10, one row in each page). I have an external template .DOCX
file ready and this action will be performed on the document itself. The code is:
File file = JFileChooser1.getSelectedFile();
XWPFDocument order=new XWPFDocument(new FileInputStream(file));
CTBody page=order.getDocument().getBody();
XWPFTable table;
for(int x=0;x<xlTab.getRowCount();x++){
table=order.getTableArray(x);
System.out.println("Tables present: "+table.toString());
for(int col=0;col<3;col++){
table.getRow(0).getCell(col).setText(xlTab.getColumnName(col)+":\n"+xlTab.getValueAt(x,col));
}
order.getDocument().AddNewBody().set(page);
}
The error I'm getting is:
Tables present: org.apache.poi.xwpf.usermodel.XWPFTable@3c1e93f9
Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index 1 out of bounds for length 1
Why does table
contain only one Table?
Edit: I'm using Java 18, and the above code is executed on a button click (for nitpickers).
Solution
Creating table through CTTbl
resolves this issue:
JFileChooser fc=new JFileChooser();
XWPFDocument template=new XWPFDocument(new FileInputStream(file)); //This is the template file
XWPFDocument intermediate=new XWPFDocument(); //all the changes will be done in this file. Directly modifying template will throw ConcurrentModificationException
CTTbl tbl=CTTbl.Factory.newInstance();
tbl.set(template.getTables().get(0).getCTTbl()); //template contains only one table.
int pos=0;
for(int i=0;i<xlTab.getRowCount();i++){
for(IBodyElement ele:template.getBodyElements()){
switch(ele.getElementType()){
case PARAGRAPH -> {
intermediate.createParagraph();
intermediate.setParagraph((XWPFParagraph)ele,pos++);
}
case TABLE -> {
intermediate.createTable();
}
case
}
}
intermediate.createParagraph().createRun().addBreak(BreakType.PAGE);
pos++;
}
XWPFTable tempTab = new XWPFTable(tbl, intermediate);
//
//Add items to tempTab here
//
intermediate.setTable(i,tempTab);
Answered By - Adnan
Answer Checked By - Candace Johnson (JavaFixing Volunteer)