Java根据word模板导出数据

package com.jeecg.ldcorder.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.jeecgframework.poi.word.WordExportUtil;

public class WordUtil {

    /**
    * EasyPoi 替换数据 导出 word
    * @param templatePath word模板地址
    * @param tempDir 临时文件存放地址
    * @param filename 文件名称
    * @param data 替换参数
    * @param request
    * @param response
    */
    public static void easyPoiExport(String templatePath, String tempDir, String filename, Map<String, Object> data, HttpServletRequest request, HttpServletResponse response) {
    if (!tempDir.endsWith("/")) {
        tempDir = tempDir + File.separator;
    }

    File file = new File(tempDir);
    if (!file.exists()) {
        file.mkdirs();
    }

    try {
        String userAgent = request.getHeader("user-agent").toLowerCase();
        if (userAgent.contains("msie") || userAgent.contains("like gecko")) {
            filename = URLEncoder.encode(filename, "UTF-8");
        } else {
            filename = new String(filename.getBytes("utf-8"), "ISO-8859-1");
        }
        //防止文件过大,报错:java.io.IOException: Zip bomb detected! The file would exceed the max
        ZipSecureFile.setMinInflateRatio(-1.0d);
        //开始导出文件操作
        XWPFDocument document = WordExportUtil.exportWord07(templatePath, data);
        String tempPath = tempDir + filename;
        FileOutputStream out = new FileOutputStream(tempPath);
        document.write(out);

        // 设置响应规则
        response.setContentType("application/force-download");
        response.addHeader("Content-Disposition", "attachment;filename=" + filename);
        OutputStream stream = response.getOutputStream();
        document.write(stream);
        stream.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        deleteTempFile(tempDir, filename);
    }
 }

    /**
    * 删除临时生成的文件
    */
    public static void deleteTempFile(String filePath, String fileName) {
        File file = new File(filePath + fileName);
        File f = new File(filePath);
        file.delete();
        f.delete();
 }
}

Word模板数据:

相关推荐
laimaxgg2 分钟前
Qt常用控件之数字显示控件QLCDNumber
开发语言·c++·qt·qt5·qt6.3
蓝天扶光6 分钟前
c++贪心系列
开发语言·c++
奔跑吧邓邓子34 分钟前
【Python爬虫(44)】分布式爬虫:筑牢安全防线,守护数据之旅
开发语言·分布式·爬虫·python·安全
非 白44 分钟前
【Java】单例模式
java·笔记·单例模式
C#Thread1 小时前
C#上位机--流程控制(IF语句)
开发语言·javascript·ecmascript
IDRSolutions_CN1 小时前
如何在 PDF 文件中嵌入自定义数据
java·经验分享·pdf·软件工程·团队开发
_风中无我。1 小时前
Spring的过滤器获取请求体中JSON参数,同时解决Controller获取不到请求体参数的问题。
java·spring·json
bing_1581 小时前
Spring Boot 中为什么 需要限流、降级和熔断?
java
ccm031 小时前
高效开发助手:深入了解Hutool工具库
java·g工具库
牵牛老人1 小时前
Qt开发中出现中文乱码问题深度解析与解决方案
开发语言·qt