1、引入poi 依赖组件
c
<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.引入库
c
import org.apache.poi.xwpf.usermodel.*;
2.初始化一个空文件,生成文档后写入文件中
c
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段落
c
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 对象创建表格
c
// 创建表格 n行*m列(创建table 时,会有一个默认一行一列的表格)
XWPFTable table = document.createTable(n, m);
table.setWidth("100%");// 表格所占文档宽度
// 获取第一行
XWPFTableRow row = table.getRow(0);// 设置表格标题行
// 标题行,每一列的名称都放入List中,可以循环设置列标题
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("方正仿宋");// 字体格式
}
* 或使用简单方式创建标题行,使用自适应样式
c
XWPFTableCell cell = rows.getCell(0);
buildAlignment(cell); // 单元格中的标题内容对齐方式
cell.setWidth("5%"); // 宽度
cell.setText("这也是一个标题");
/**
* 设置单元格样式
* @param cell cell
*/
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对象 写入文件中
c
FileOutputStream fos= new FileOutputStream(file);
document.write(fos);
fos.close(); // 关闭流增加判断,不可直接关闭
// docx文件创建结束!