I'm trying to create docx documents using Apache POI. However, when I open the created documents in Microsoft Word, the result is different from when I open it with LibreOffice Writer. I experienced this behavior with tables and cross references.
I would like to know if it is necessary to make any configuration to save the output format in Microsoft Word format.
For example, the code below creates a docx document containing a table with 2 rows and 2 columns:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
public class DocWithTable {
public static final int NUM_ROWS = 2;
public static final int NUM_COLS = 2;
public static void main(String[] args) throws IOException {
XWPFDocument document = new XWPFDocument();
XWPFTable table = document.createTable();
XWPFTableRow firstRow = table.getRow(0);
for (int c = 1; c < NUM_COLS; c++) {
firstRow.addNewTableCell().getCTTc().addNewTcPr();
}
for (int r = 1; r < NUM_ROWS; r++) {
table.createRow();
}
FileOutputStream out = new FileOutputStream(new File("file.docx"));
document.write(out);
out.close();
document.close();
}
}
When I open the create document with Microsoft Word, I get the following result:
When I open it with LibreOffice Writer, I get the following result:
Also, after saving the document in LibreOffice, it is opened as expected in Microsoft Word.
apache poi
the latest stable version always should be used. Else code becomes outdated very fast. And there is no reason for not using the latest stable version, is there? - Axel Richter