org.apache.poi 编写word文档
- 导入依赖
- 使用poi生成段落
- poi 在word中生成表格
- 1.生成表格对象
- 2.设置表格边框
- 3. 设置表格内文本
- 4.设置行高
导入依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.17</version>
</dependency>
使用poi生成段落
private XWPFRun setCustomizeOptionParagraph(Integer indentationLeft, ParagraphAlignment align) {
XWPFParagraph nestOptionParagraph = document.createParagraph();
nestOptionParagraph.setIndentationLeft(indentationLeft);
nestOptionParagraph.setAlignment(align);
nestOptionParagraph.setVerticalAlignment(TextAlignment.CENTER);
XWPFRun nestOptionRun = nestOptionParagraph.createRun();
nestOptionRun.setFontFamily("宋体");
nestOptionRun.setColor("000000");
nestOptionRun.setFontSize(9);
nestOptionRun.setBold(true);
nestOptionRun.addCarriageReturn();
return nestOptionRun;
}
poi 在word中生成表格
1.生成表格对象
private XWPFTable setTableWidth(Integer width, Integer rows, Integer cols) {
XWPFTable infoTable = document.createTable(rows, cols);
CTTblWidth infoTableWidth = infoTable.getCTTbl().addNewTblPr().addNewTblW();
infoTableWidth.setType(STTblWidth.DXA);
infoTableWidth.setW(BigInteger.valueOf(width));
return infoTable;
}
2.设置表格边框
private void setTableBorder(XWPFTable infoTable) {
CTTbl ctTbl = infoTable.getCTTbl();
CTTblBorders borders = ctTbl.getTblPr().addNewTblBorders();
String borderColor = "000000";
CTBorder lBorder = borders.addNewLeft();
lBorder.setVal(STBorder.DOT_DOT_DASH);
lBorder.setSz(new BigInteger("1"));
lBorder.setColor(borderColor);
CTBorder rBorder = borders.addNewRight();
rBorder.setVal(STBorder.DOT_DOT_DASH);
rBorder.setSz(new BigInteger("1"));
rBorder.setColor(borderColor);
CTBorder tBorder = borders.addNewTop();
tBorder.setVal(STBorder.DOT_DOT_DASH);
tBorder.setSz(new BigInteger("1"));
tBorder.setColor(borderColor);
CTBorder bBorder = borders.addNewBottom();
bBorder.setVal(STBorder.DOT_DOT_DASH);
bBorder.setSz(new BigInteger("1"));
bBorder.setColor(borderColor);
}
3. 设置表格内文本
private void setCustomizeTableParagraph(XWPFTableCell cell, String text, TextAlignment valign, ParagraphAlignment align) {
CTP ctp = CTP.Factory.newInstance();
XWPFParagraph p = new XWPFParagraph(ctp, cell);
p.setAlignment(align);
p.setVerticalAlignment(valign);
XWPFRun run = p.createRun();
run.setText(text);
run.setFontSize(9);
run.setColor("000000");
run.setFontFamily("宋体");
cell.setParagraph(p);
}
4.设置行高
infoTable.getRow(0).setHeight(2800);
5.设置单元格背景色
infoTableRow.getCell(0).setColor(gray);
6.合并单元格
private void setMergeCell(int row, int cellIndex, XWPFTableCell cell) {
if (row == 0) {
if (cellIndex == 1) {
cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
} else {
cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
}
}
if (cellIndex == 0) {
if (row == 0) {
cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
}
if (row == 1) {
cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
}
cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
}
}