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

相关推荐
落羽的落羽4 小时前
【C++】哈希扩展——位图和布隆过滤器的介绍与实现
linux·服务器·开发语言·c++·人工智能·算法·机器学习
fish_xk5 小时前
类和对象(二)
开发语言·c++·算法
lly2024065 小时前
Python 列表(List)详解
开发语言
Han.miracle5 小时前
Spring Boot 项目从入门到排障:核心结构、依赖管理与启动全解析
java·jar
深蓝电商API5 小时前
从 “能爬” 到 “稳爬”:Python 爬虫中级核心技术实战
开发语言·爬虫·python
麦麦鸡腿堡5 小时前
Java_通过反射获取类的结构信息
java·开发语言
还是鼠鼠5 小时前
SQL语句执行很慢,如何分析呢?
java·数据库·mysql·面试
爱装代码的小瓶子5 小时前
【c++知识铺子】封装map和set(详细版)
android·java·c++
2201_757830875 小时前
tlias的部门的增删改查操作
java·开发语言
云和数据.ChenGuang5 小时前
批量给100台服务器装系统,还要完成后续的配置和软件部署
运维·服务器·开发语言·mysql