Java如何根据word模板导出数据

2025-05-19 02:50
文章标签 java word 模板 导出 数据

本文主要是介绍Java如何根据word模板导出数据,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《Java如何根据word模板导出数据》这篇文章主要为大家详细介绍了Java如何实现根据word模板导出数据,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下...

pom.XML文件导入依赖 

<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-spring-boot-starter</artifactId>
    <version>4.4.0</version>
</dependency>

以下为导出代码: 

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 文件名称
    * @paraChina编程m 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
php        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模板数据效果:

Java如何根据word模板导出数据

方法补充

java实现根据word模板导出数据

模板文件:

Java如何根据word模板导出数据

模板描述:{{?govinspectItemVOList}} 为循环遍历的数据实体

代码块:

//生成文件所在路径
String dirName = System.getProperty("user.dir") + File.separator + "file";
//模板文件存放地址
String templateFileName = dirName + File.separator + "质量安全巡查检查报告.docx";
//生成的临时文件
String fileName = "质量安全巡查检查报告" + System.currentTimeMillis() + ".docx";
WordUtils.fill(response, dirName, fileName, templateFileName, exportProjectReportVO);
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.util.FileUtils;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.config.ConfigureBuilder;
import lombok.SneakyThrows;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
public class WordUtils {
	/**
     * @param response         输出流
     * @param path             生成文件所在路径
     * @param filename         文件名称
     * @param templateFileName 模板名称 全路径,包含模板名称
     * @param data             组装的数据
     * @throws IOException
     */
	public static <T> void fill(HttpServletResponse response, String path, String filename, String templateFileName,
                                Object data) throws IOException, IllegalAccessException {
        Map<String, Object> templateData = new HashMap<>();
        ConfigureBuilder builder = Configure.builder();
        /**遍历数据*/
        for (Field field : data.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            Object value = field.get(data);
            if (ObjectUtil.isNull(value)) {
                value = "";
            }
            Strinphpg subClassName = value.getClass().getSimpleName();
            if (Arrays.asList(ApiConstants.classNames).contains(subClassName)) {
                templateData.put(field.getName(), value);
            } else {
                if (value instanceof List<?>) {
                    //list 创建 tables
                    List<?> subList = (List<?>) value;
                    templateData.put(field.getName(), createTable(subList));
                }
            }
        }
        Configure config = builder.build();
        // 4. 创建模板,输出模板
        String tempName = templateFileName;
        XWPFTemplate template = XWPFTemplate.compile(tempName, config)
                .render(templateData);
        Filejavascript outputFile = new File(path + File.separator + filename);
        template.writeToFileandroid(path + File.separator + filename);
        template.close();

        if (outputFile.exists()) {
            FileInputStream fis = new FileInputStream(outputFile);
            ServletOutputStream sos = response.getOutputStream();
            int len;
            byte[] readBytes = new byte[1024];
            while ((len = fis.read(readBytes)) != -1) {
                sos.write(readBytes, 0, len);
            }
            fis.close();
            // 输出 Excel
            sos.flush();
            sos.close();
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8));
            response.setContentType("application/octet-stream");
            //删除临时文件
            outputFile.delete();
        }
        // 设置 header 和 contentType。写在最后的原因是,避免报错时,响应 contentType 已经被修改了

    }
 }

到此这篇关于Java如何根据word模板导出数据的文章就介绍到这了,更多相关Java根据word模板导出数据内容请搜索China编程(www.chinasem.cn)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程China编程(www.chinasem.cn)!

这篇关于Java如何根据word模板导出数据的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1154665

相关文章

SpringSecurity显示用户账号已被锁定的原因及解决方案

《SpringSecurity显示用户账号已被锁定的原因及解决方案》SpringSecurity中用户账号被锁定问题源于UserDetails接口方法返回值错误,解决方案是修正isAccountNon... 目录SpringSecurity显示用户账号已被锁定的解决方案1.问题出现前的工作2.问题出现原因各

Java继承映射的三种使用方法示例

《Java继承映射的三种使用方法示例》继承在Java中扮演着重要的角色,它允许我们创建一个类(子类),该类继承另一个类(父类)的所有属性和方法,:本文主要介绍Java继承映射的三种使用方法示例,需... 目录前言一、单表继承(Single Table Inheritance)1-1、原理1-2、使用方法1-

Oracle 数据库数据操作如何精通 INSERT, UPDATE, DELETE

《Oracle数据库数据操作如何精通INSERT,UPDATE,DELETE》在Oracle数据库中,对表内数据进行增加、修改和删除操作是通过数据操作语言来完成的,下面给大家介绍Oracle数... 目录思维导图一、插入数据 (INSERT)1.1 插入单行数据,指定所有列的值语法:1.2 插入单行数据,指

Spring @Scheduled注解及工作原理

《Spring@Scheduled注解及工作原理》Spring的@Scheduled注解用于标记定时任务,无需额外库,需配置@EnableScheduling,设置fixedRate、fixedDe... 目录1.@Scheduled注解定义2.配置 @Scheduled2.1 开启定时任务支持2.2 创建

SpringBoot中使用Flux实现流式返回的方法小结

《SpringBoot中使用Flux实现流式返回的方法小结》文章介绍流式返回(StreamingResponse)在SpringBoot中通过Flux实现,优势包括提升用户体验、降低内存消耗、支持长连... 目录背景流式返回的核心概念与优势1. 提升用户体验2. 降低内存消耗3. 支持长连接与实时通信在Sp

Spring Boot 实现 IP 限流的原理、实践与利弊解析

《SpringBoot实现IP限流的原理、实践与利弊解析》在SpringBoot中实现IP限流是一种简单而有效的方式来保障系统的稳定性和可用性,本文给大家介绍SpringBoot实现IP限... 目录一、引言二、IP 限流原理2.1 令牌桶算法2.2 漏桶算法三、使用场景3.1 防止恶意攻击3.2 控制资源

Mac系统下卸载JAVA和JDK的步骤

《Mac系统下卸载JAVA和JDK的步骤》JDK是Java语言的软件开发工具包,它提供了开发和运行Java应用程序所需的工具、库和资源,:本文主要介绍Mac系统下卸载JAVA和JDK的相关资料,需... 目录1. 卸载系统自带的 Java 版本检查当前 Java 版本通过命令卸载系统 Java2. 卸载自定

springboot下载接口限速功能实现

《springboot下载接口限速功能实现》通过Redis统计并发数动态调整每个用户带宽,核心逻辑为每秒读取并发送限定数据量,防止单用户占用过多资源,确保整体下载均衡且高效,本文给大家介绍spring... 目录 一、整体目标 二、涉及的主要类/方法✅ 三、核心流程图解(简化) 四、关键代码详解1️⃣ 设置

Java Spring ApplicationEvent 代码示例解析

《JavaSpringApplicationEvent代码示例解析》本文解析了Spring事件机制,涵盖核心概念(发布-订阅/观察者模式)、代码实现(事件定义、发布、监听)及高级应用(异步处理、... 目录一、Spring 事件机制核心概念1. 事件驱动架构模型2. 核心组件二、代码示例解析1. 事件定义

SpringMVC高效获取JavaBean对象指南

《SpringMVC高效获取JavaBean对象指南》SpringMVC通过数据绑定自动将请求参数映射到JavaBean,支持表单、URL及JSON数据,需用@ModelAttribute、@Requ... 目录Spring MVC 获取 JavaBean 对象指南核心机制:数据绑定实现步骤1. 定义 Ja