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

相关推荐
开心码农1号22 分钟前
Java rabbitMQ如何发送、消费消息、全套可靠方案
java·rabbitmq·java-rabbitmq
EAIReport25 分钟前
国外网站数据批量采集技术实现路径
开发语言·python
超绝振刀怪26 分钟前
【C++可变模板参数】
开发语言·c++·可变模板参数
蜡台31 分钟前
JetBrains IDEA 安装 卸载相关总结
java·ide·intellij-idea·注册码
WJLSH12332 分钟前
TomCat
java·tomcat
Freak嵌入式36 分钟前
MicroPython LVGL基础知识和概念:时序与动态效果
开发语言·python·github·php·gui·lvgl·micropython
戮戮1 小时前
Spring Cloud Gateway 零拷贝参数校验:一种高性能网关架构实践
java·网络·架构·gateway
2501_933329551 小时前
企业媒体发布与舆情管理实战:Infoseek舆情系统技术架构与落地解析
大数据·开发语言·人工智能·数据库开发
"菠萝"1 小时前
C#知识学习-021(文字关键字)
开发语言·学习·c#