SpringBoot集成 Apache POI Word(docx)
- pom文件添加依赖- <dependency>
- <groupId>org.apache.poi</groupId>
- <artifactId>poi</artifactId>
- <version>4.1.2</version>
- </dependency>
- <dependency>
- <groupId>org.apache.poi</groupId>
- <artifactId>poi-ooxml</artifactId>
- <version>4.1.2</version>
- </dependency>
 
- 创建新文档- XWPFDocument doc = new XWPFDocument();
 
- 创建段落- XWPFParagraph para1 = doc.createParagraph();
 
- 设置对其方式- // 对齐方式 居中
- para1.setAlignment(ParagraphAlignment.CENTER);
- // 对齐方式 居右
- para1.setAlignment(ParagraphAlignment.RIGHT);
- // 对齐方式 居左
- para1.setAlignment(ParagraphAlignment.LEFT);
 
- 创建基本元素XWPFRun
 创建好段落后,我们就可以通过相关API处理段落内的文本和图片了。XWPFRun是段落的基本组成单元,它可以是一个文本,也可以是一张图片。- XWPFRun run1 = para1.createRun();
 
- 设置字体大小和颜色- run1.setFontSize(18);
- run1.setColor("FF0000");
 
- 设置下划线和加粗- run1.setUnderline(UnderlinePatterns.SINGLE);//下划线样式
- run1.setBold(true);//true表示加粗
 
- 设置超链接- XWPFHyperlinkRun hyperlinkrun = para4.createHyperlinkRun("URL"); //超链接的地址
- hyperlinkrun.setText("原文链接");//超链接文本
 
- 设置换行和缩进- //换行
- run1.addCarriageReturn();
- //缩进
- run1.addTab();
 
- 写入到word文件中- //导出文件名称
- String exportFile = "D:/temp/test.docx";
- // word写入到文件
- FileOutputStream fos = new FileOutputStream(exportFile);
- doc.write(fos);
- fos.close();