问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

使用POI-TL通过Word模板生成Word文件

创作时间:
作者:
@小白创作中心

使用POI-TL通过Word模板生成Word文件

引用
CSDN
1.
https://blog.csdn.net/moshowgame/article/details/81702029

技术背景

在网站或系统开发中,常常需要生成Word文件供用户下载打印,例如证明文件或订单文件。Apache POI是Java操作Word文档最流行的库,本文将介绍如何使用POI-TL库通过Word模板生成Word文件。

Maven依赖

要使用POI-TL库,需要在项目的pom.xml文件中添加以下依赖:

<dependency>
    <groupId>com.deepoove</groupId>
    <artifactId>poi-tl</artifactId>
    <version>1.3.1</version>
</dependency>

核心实现代码

以下是一个简单的示例,展示了如何通过一个制作好的Word模板文件,填充数据生成新的Word文件:

@RestController
public class PoiController {

    @GetMapping("/generateWord")
    public ApiReturnObject generateWord(String data) {
        // 模板文件路径
        String wordPath = "C:\\Users\\Administrator\\Desktop\\";
        String modelName = "人物模板.docx";
        String outputName = "hanyunxi.docx";

        // 准备数据
        Map<String, Object> datas = new HashMap<>();
        datas.put("name", "鞠婧祎");
        datas.put("team", "前SNH48");
        datas.put("gender", "女");
        datas.put("birthday", "19940618");
        datas.put("remark", "鞠婧祎,1994年6月18日出生于四川遂宁,毕业于四川音乐学院附属中学,中国女演员、歌手,原SNH48 TEAM NII成员");

        // 填充数据并生成新的Word文件
        XWPFTemplate template = XWPFTemplate.compile(wordPath + modelName).render(datas);
        try (FileOutputStream out = new FileOutputStream(wordPath + outputName)) {
            template.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ApiReturnUtil.success(data);
    }
}

支持的模板标签

POI-TL支持多种类型的模板标签,包括文本、图片、表格和编号列表等。以下是一些示例:

  • 文本标签:

    put("author", new TextRenderData("000000", "Sayi卅一"));
    put("introduce", "http://www.deepoove.com");
    
  • 图片标签:

    put("localPicture", new PictureRenderData(120, 120, "./sayi.png"));
    
  • 表格标签:

    put("changeLog", new TableRenderData(
        new ArrayList<RenderData>() {{
            add(new TextRenderData("d0d0d0", ""));
            add(new TextRenderData("d0d0d0", "introduce"));
        }},
        new ArrayList<Object>() {{
            add("1;add new # gramer");
            add("2;support insert table");
            add("3;support more style");
        }},
        "no datas", 10600));
    
  • 编号列表标签:

    put("feature", new NumbericRenderData(new ArrayList<TextRenderData>() {{
      add(new TextRenderData("Plug-in grammar"));
      add(new TextRenderData("Supports word text, header..."));
      add(new TextRenderData("Not just templates, but also style templates"));
    }}));
    

运行效果

以下是生成的Word文件的运行效果截图:

注意事项

如果在使用过程中遇到以下错误:

org.apache.poi.openxml4j.exceptions.OLE2NotOfficeXmlFileException: The supplied data appears to be in the OLE2 Format. You are calling the part of POI that deals with OOXML (Office Open XML) Documents. You need to call a different part of POI to process this data (eg HSSF instead of XSSF)

这通常是因为文件后缀名错误。POI-TL封装的是docx格式的版本,因此需要确保使用的模板文件是docx格式。

© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号