一、maven导入
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-examples</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-excelant</artifactId>
<version>4.1.2</version>
</dependency>
二、开始使用
1、创建 XWPFDocument对象
创建出该对象,可以对应生成docx类型的文件
XWPFDocument document = new XWPFDocument();
2、生成文档
try {
String path = "";//生成文档的路径
String fileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")) + StringTool.getGuid() + ".docx";//生成文件的文件名,需要携带文件后缀
FileOutputStream out = new FileOutputStream(path + fileName);//创建文件流
document .write(out);//将XWPFDocument对象中的数据写入流中
out.close();//关闭流
} catch (IOException e) {
e.printStackTrace();
}
3、创建段落
该段落作用可以类比到html中的div
XWPFParagraph paragraph = doc.createParagraph();
将该段落设置为水平居中
paragraph.setAlignment(ParagraphAlignment.CENTER);
4、创建文本对象
XWPFRun run = paragraph.createRun();
相关属性作用
run.setText(" ");//设置该文本对象的文字内容
run.setFontFamily("宋体");//设置该文本对象使用的字体
run.setFontSize((int) 10.5);//设置该文本对象的字体大小。最好为整数
run.setBold(true);设置字体是否加粗,true为加粗,false为不加粗