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模板数据:

相关推荐
Wpa.wk2 分钟前
selenium自动化测试-简单PO模式 (java版)
java·自动化测试·selenium·测试工具·po模式
洛_尘10 分钟前
JAVA第十一学:认识异常
java·开发语言
沐浴露z27 分钟前
如何应对服务雪崩?详解 服务降级与服务熔断
java·微服务
毕设源码-邱学长28 分钟前
【开题答辩全过程】以 基于JavaScript的图书销售网站为例,包含答辩的问题和答案
开发语言·javascript·ecmascript
liwulin050634 分钟前
【JAVA】AES加密
java
阿宁又菜又爱玩41 分钟前
Maven基础知识
java·maven
S***q37744 分钟前
【Springboot】@Autowired和@Resource的区别
java·spring boot·mybatis
老王熬夜敲代码44 分钟前
泛型编程的差异抽象思想
开发语言·c++·笔记
南部余额44 分钟前
SpringBoot自定义场景启动器
java·spring boot·场景启动器
p***s911 小时前
【SpringBoot】日志文件
java·spring boot·spring