springboot实现Word文档(包含图片)生成

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
/**
 * @author LMY
 * @email 2269467209@qq.com
 */
public class WordTest {
     @Test
    public  void exportword() throws IOException, InvalidFormatException {
        XWPFDocument doc = new XWPFDocument();
        //创建一个段落
        XWPFParagraph paragraph = doc.createParagraph();
        //设置标题
//        paragraph.setStyle("标题 1");
        //一个XWPFRun代表具有相同属性的一个区域:一段文本
        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();
//         XWPFParagraph wordparagraph = doc.createParagraph();
//         XWPFRun run3 =wordparagraph.createRun();
        //插入图片
        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输出到输出流
        doc.write(os);
        doc.close();
    }

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值