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

相关推荐
狂奔的sherry21 分钟前
单例模式(巨通俗易懂)普通单例,懒汉单例的实现和区别,依赖注入......
开发语言·c++·单例模式
Volunteer Technology1 小时前
三高项目-缓存设计
java·spring·缓存·高并发·高可用·高数据量
EnigmaCoder1 小时前
【C++】引用的本质与高效应用
开发语言·c++
栗子~~1 小时前
bat脚本- 将jar 包批量安装到 Maven 本地仓库
java·maven·jar
Mr.Entropy1 小时前
ecplise配置maven插件
java·maven
zhangfeng11332 小时前
BiocManager下载失败 R语言 解决办法
开发语言·r语言
叙白冲冲2 小时前
tomcat 为啥能一直运行?不像方法那样结束?
java·tomcat
CoderYanger2 小时前
MySQL数据库——3.2.1 表的增删查改-查询部分(全列+指定列+去重)
java·开发语言·数据库·mysql·面试·职场和发展
迷知悟道2 小时前
java面向对象四大核心特征之抽象---超详细(保姆级)
java·后端
炮院李教员2 小时前
使用Qt Core模块(无GUI依赖),确保程序作为后台服务/daemon运行,与任何GUI完全无交互。
开发语言·qt