记录一次关于java 导出word的代码

记录一次关于java 导出word的代码

public class WordService {

    public void exportWord(String title) throws IOException {

        River river = new River();
        XWPFTemplate template1 = XWPFTemplate.compile("~/Users/liwenna/Documents/" + "template.docx").render(river);

        RowRenderData row0 = Rows.of("姓名", "性别", "学费信息", "", "", "年龄").center().create();
        XWPFTemplate template = XWPFTemplate.compile("template.docx").render(
                new HashMap<String, Object>(){{
                    put("title", "Hi, poi-tl Word模板引擎");
                }});

        template.writeToFile("output.docx");
    }


    public void exportFile() throws Exception {
        String wordPath = "pwd";
        String modelName = "template.docx";
        String outputName = "test1.docx";
        PictureRenderData picture = Pictures.ofUrl("url", PictureType.PNG).size(100, 100).create();
        PictureRenderData netPicture = Pictures.ofUrl("url", PictureType.PNG).size(100, 100).create();

        // 表格
        List<RowRenderData> row = new ArrayList<>();
        row.add(Rows.of("小明", "男", "2000", "5000", "1", "18").center().create());
        row.add(Rows.of("小红", "女", "3000", "8000", "1", "18").center().create());

        RowRenderData row0 = Rows.of("firstrow", "", "", "", "", "").center().create();
        RowRenderData row1 = Rows.of("cow1", "cow2", "cow3", "cow4", "cow5", "cow6").center().create();
        // 表格合并
        MergeCellRule rule = MergeCellRule.builder().map(
                MergeCellRule.Grid.of(0, 0), MergeCellRule.Grid.of(0, 5)).
                build();
        TableRenderData table = Tables.of(row0, row1, row.iterator().next()).mergeRule(rule).create();
        // 数据封装
        UserInfo userInfo = new UserInfo();
        userInfo.setTitle("name");
        userInfo.setGender("gender");
        userInfo.setRemark("remark");
        userInfo.setPicture(picture);
        userInfo.setNetPicture1(netPicture);
        userInfo.setTable(table);
        // 传入模板模板地址+信息数据
        XWPFTemplate template = XWPFTemplate.compile(wordPath + modelName).render(userInfo);
        FileOutputStream out;
        try {
            // 将结果输出到目标位置
            out = new FileOutputStream(wordPath + outputName);
            template.write(out);
            out.flush();
            out.close();
            template.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值