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

相关推荐
yuan199971 分钟前
基于扩展卡尔曼滤波的电池荷电状态估算的MATLAB实现
开发语言·matlab
Tony Bai3 分钟前
Go GUI 开发的“绝境”与“破局”:2025 年现状与展望
开发语言·后端·golang
豆浆whisky3 分钟前
Go分布式追踪实战:从理论到OpenTelemetry集成|Go语言进阶(15)
开发语言·分布式·golang
2401_860494703 分钟前
Rust语言高级技巧 - RefCell 是另外一个提供了内部可变性的类型,Cell 类型没办法制造出直接指向内部数据的指针,为什么RefCell可以呢?
开发语言·rust·制造
Tony Bai4 分钟前
【Go模块构建与依赖管理】08 深入 Go Module Proxy 协议
开发语言·后端·golang
浪裡遊4 分钟前
Next.js路由系统
开发语言·前端·javascript·react.js·node.js·js
程序员-小李5 分钟前
基于 Python + OpenCV 的人脸识别系统开发实战
开发语言·python·opencv
QX_hao6 分钟前
【Go】--文件和目录的操作
开发语言·c++·golang
卡提西亚7 分钟前
C++笔记-20-对象特性
开发语言·c++·笔记
Deamon Tree25 分钟前
【设计题】如何实现限流器
java