1、引入poi 依赖组件
<dependency><groupId>org.apache.poi</groupId><artifactId>poi-scratchpad</artifactId><version>4.0.0</version>
</dependency>
<dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.2</version>
</dependency>
2、使用
1.引入库
import org.apache.poi.xwpf.usermodel.*;
2.初始化一个空文件,生成文档后写入文件中
public static File createFile() {Filefile = null;try {String path = "./testFile.docx";Path path2 = Paths.get(path);boolean exists = Files.exists(path2);if (exists) {Files.delete(path2);file = new File(path);} else {file = new File(path);}} catch (IOException e) {log.error("初始化file失败", e.getMessage());}return file;
}
3.创建 XWPFDocument 对象,create段落
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
paragraph .setAlignment(ParagraphAlignment.CENTER);
XWPFRun run = paragraph .createRun();
run.setText("这是一段文字,代表一个段落内容!");
run.setBold(true);
run.setFontSize(18);
run.setFontFamily("微软雅黑");
run.addCarriageReturn();
run.setKerning(30);
段落循环创建
4.使用 XWPFDocument 对象创建表格
XWPFTable table = document.createTable(n, m);
table.setWidth("100%");
XWPFTableRow row = table.getRow(0);
List<String> titles = Lists.newArrayList();
for (int i = 0; i < titles.size(); i++) {XWPFTableCell cell0 = row.getCell(i);cell0.setWidth(width + "%"); cell0.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); XWPFParagraph paragraph = cell0.addParagraph();paragraph.setAlignment(ParagraphAlignment.CENTER);XWPFRun run = paragraph.createRun();run.setText("这是一个标题");run.setFontSize(16);run.setBold(true);run.setFontFamily("方正仿宋");
}
* 或使用简单方式创建标题行,使用自适应样式
XWPFTableCell cell = rows.getCell(0);
buildAlignment(cell);
cell.setWidth("5%");
cell.setText("这也是一个标题");
private static void buildAlignment(XWPFTableCell cell) {CTTcPr cellPr = cell.getCTTc().getTcPr() == null ? cell.getCTTc().addNewTcPr() : cell.getCTTc().getTcPr();if (cellPr.getVAlign() == null) {cellPr.addNewVAlign().setVal(STVerticalJc.CENTER);} else {cellPr.getVAlign().setVal(STVerticalJc.CENTER);}XWPFParagraph paragraph1=cell.getParagraphArray(0);paragraph1.setAlignment(ParagraphAlignment.CENTER);
}
5.将创建的XWPFDocument对象 写入文件中
FileOutputStream fos= new FileOutputStream(file);
document.write(fos);
fos.close();
up