1.需求分析
根据指定内容生成一个包含图片的Word文档,保存在本地
2.用到的工具
org.apache.poi
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>
3.代码
@RunWith(SpringRunner.class)
@SpringBootTest
public class WordTest {
@Test
public void exportword() throws IOException, InvalidFormatException {
XWPFDocument doc = new XWPFDocument();
XWPFParagraph paragraph = doc.createParagraph();
XWPFRun run1 =paragraph.createRun();
run1.setText(" Word报告");
run1.setBold(true);
run1.setColor("000000");
run1.setFontFamily("宋体");
run1.setFontSize(20);
XWPFRun run2 =paragraph.createRun();
run2.setText(" 人的一生应当这样度过:当回忆往事的时候,他不会因为虚度年华而悔恨,也不会因为碌碌无为而感到羞愧;在临死的时候,他能说:“我的整个生命和全部精力,都已经献给了世界最壮丽的事业--为人类的解放而斗争。");
run2.setColor("000000");
run2.setFontFamily("宋体");
run2.setFontSize(12);
run1.addCarriageReturn();
run2.addPicture(new FileInputStream("C:\\Users\\Administrator\\Desktop\\新建文件夹\\图片.jpg"),
XWPFDocument.PICTURE_TYPE_PNG,
"1.png",
Units.toEMU(300),
Units.toEMU(300));
String path="C:\\Users\\Administrator\\Desktop\\新建文件夹\\"+ "文件名"+".docx";
OutputStream os = new FileOutputStream(path);
doc.write(os);
doc.close();
}