среда, 4 декабря 2013 г.

Apache POI 3.9 DOCX Cookbook

Here is my cookbook recipes for working with Apache POI 3.9 and DOCX.

Api for DOCX in Apache POI is scarce.

1) It is difficult to grab the terminology at first. To understand the terminology you can look at the http://officeopenxml.com. This site contains the information about the structure of DOCX format.

2) Create paragraph and center it:
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
paragraph.setAlignment(ParagraphAlignment.CENTER);

3) Fill the paragraph with bold text, size 16 and break after it:
XWPFRun paragraphRun = paragraph.createRun();
paragraphRun.setBold(true);
paragraphRun.setText("my text");
paragraphRun.setFontSize(16);
paragraphRun.addBreak();

4) Merge 2 cells in table (like colspan attribute in html):
XWPFTable table = document.createTable();
XWPFTableRow row = table.getRow(0);
row.getCell(0).setText("my cell);
// get a table cell properties element (tcPr)
CTTcPr tcpr = row.getCell(0).getCTTc().addNewTcPr();
// set gridspan
CTDecimalNumber gridSpan = tcpr.addNewGridSpan();
gridSpan.setVal(new BigInteger("2")); <-- the colspan of cell

5) Set background of cell:
// set fill color
 CTShd ctshd = tcpr.addNewShd();
 ctshd.setColor("auto");
 ctshd.setVal(STShd.CLEAR);
 ctshd.setFill("E3E7E9"); <--  RGB color

6) Set width of cell to 100%:
// setwidth
CTTblWidth cttblwidth = tcpr.addNewTcW();
cttblwidth.setW(BigInteger.valueOf(100));
cttblwidth.setType(STTblWidth.PCT);