java使用poi-tl模版引擎导出word之列表循环数据渲染

目录

poi-tl模版引擎中,如果区块对的值是一个非空集合,区块中的文档元素会被迭代渲染一次或者N次,这取决于集合的大小,类似于foreach语法。

1.模版制作

在静态资源目录下resources/static/templates新建exportWord.docx,编写以下模版内容:

2.开启spring表达式

(1)引入依赖

xml 复制代码
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-expression</artifactId>
    <version>5.3.18</version>
</dependency>

(2)代码中开启表达式

java 复制代码
ConfigureBuilder builder = Configure.builder();
// 开启spring表达式
builder.useSpringEL();

3.编写关键代码接口

java 复制代码
@GetMapping("/exportWord")
public void exportWord(HttpServletResponse response) throws FileNotFoundException {
    //存放数据,也就是填充在word里面的值
    Map<String, Object> params = new HashMap<>();
    params.put("title","测试使用poi-tl模版导出word");

    List<Map<String, Object>> list = new ArrayList<>();
    Map<String, Object> map = new HashMap<>();
    map.put("a","测试");
    map.put("b","米");
    map.put("c","201312");
    list.add(map);
    Map<String, Object> map1 = new HashMap<>();
    map1.put("a","测试2");
    map1.put("b","千米");
    map1.put("c","2012312");
    list.add(map1);

    params.put("list",list);

    ConfigureBuilder builder = Configure.builder();
    // 开启spring表达式
    builder.useSpringEL();

    // 或模板在静态资源的相对路径
    File rootFile = new File((ResourceUtils.getURL("classpath:").getPath()));
    File templateFile = new File(rootFile, "/static/templates/exportWord.docx");
    //jar包获取不到文件路径`
    //URLDecoder.decode() 解决获取中文名称文件路径乱码
    String templatePath = URLDecoder.decode(templateFile.getPath());
    //生成文件名
    String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + System.currentTimeMillis();
    // 导出wold
    try {
        // 导出Word文档为文件
        XWPFTemplate template = XWPFTemplate.compile(templatePath,builder.build()).render(params);
        // 将导出的Word文件转换为流
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition","attachment;filename=\""+fileName+".docx"+"\"");
        // HttpServletResponse response
        OutputStream out = response.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(out);
        template.write(bos);
        bos.flush();
        out.flush();
        // 最后不要忘记关闭这些流。
        PoitlIOUtils.closeQuietlyMulti(template, bos, out);
    } catch (Exception e) {
        System.out.println("导出Word文档时出现异常:" + e.getMessage());
    }
}

4. 导出结果

相关推荐
迷迭所归处11 分钟前
C++ —— 关于vector
开发语言·c++·算法
架构文摘JGWZ39 分钟前
Java 23 的12 个新特性!!
java·开发语言·学习
leon62540 分钟前
优化算法(一)—遗传算法(Genetic Algorithm)附MATLAB程序
开发语言·算法·matlab
拾光师2 小时前
spring获取当前request
java·后端·spring
aPurpleBerry2 小时前
neo4j安装启动教程+对应的jdk配置
java·neo4j
锦亦之22332 小时前
QT+OSG+OSG-earth如何在窗口显示一个地球
开发语言·qt
我是苏苏2 小时前
Web开发:ABP框架2——入门级别的增删改查Demo
java·开发语言
姜太公钓鲸2332 小时前
c++ static(详解)
开发语言·c++
菜菜想进步2 小时前
内存管理(C++版)
c语言·开发语言·c++
xujinwei_gingko2 小时前
Spring IOC容器Bean对象管理-Java Config方式
java·spring