亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Java如何根據(jù)word模板導(dǎo)出數(shù)據(jù)

 更新時間:2025年05月18日 14:03:41   作者:MartinYangHJ  
這篇文章主要為大家詳細(xì)介紹了Java如何實現(xiàn)根據(jù)word模板導(dǎo)出數(shù)據(jù),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下

pom.xml文件導(dǎo)入依賴 

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

以下為導(dǎo)出代碼: 

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 替換數(shù)據(jù) 導(dǎo)出 word
    * @param templatePath word模板地址
    * @param tempDir 臨時文件存放地址
    * @param filename 文件名稱
    * @param data 替換參數(shù)
    * @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);
        //開始導(dǎo)出文件操作
        XWPFDocument document = WordExportUtil.exportWord07(templatePath, data);
        String tempPath = tempDir + filename;
        FileOutputStream out = new FileOutputStream(tempPath);
        document.write(out);
 
        // 設(shè)置響應(yīng)規(guī)則
        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模板數(shù)據(jù)效果:

方法補充

java實現(xiàn)根據(jù)word模板導(dǎo)出數(shù)據(jù)

模板文件:

模板描述:{{?govinspectItemVOList}} 為循環(huán)遍歷的數(shù)據(jù)實體

代碼塊:

//生成文件所在路徑
String dirName = System.getProperty("user.dir") + File.separator + "file";
//模板文件存放地址
String templateFileName = dirName + File.separator + "質(zhì)量安全巡查檢查報告.docx";
//生成的臨時文件
String fileName = "質(zhì)量安全巡查檢查報告" + 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             組裝的數(shù)據(jù)
     * @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();
        /**遍歷數(shù)據(jù)*/
        for (Field field : data.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            Object value = field.get(data);
            if (ObjectUtil.isNull(value)) {
                value = "";
            }
            String subClassName = value.getClass().getSimpleName();
            if (Arrays.asList(ApiConstants.classNames).contains(subClassName)) {
                templateData.put(field.getName(), value);
            } else {
                if (value instanceof List<?>) {
                    //list 創(chuàng)建 tables
                    List<?> subList = (List<?>) value;
                    templateData.put(field.getName(), createTable(subList));
                }
            }
        }
        Configure config = builder.build();
        // 4. 創(chuàng)建模板,輸出模板
        String tempName = templateFileName;
        XWPFTemplate template = XWPFTemplate.compile(tempName, config)
                .render(templateData);
        File outputFile = new File(path + File.separator + filename);
        template.writeToFile(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();
        }
        // 設(shè)置 header 和 contentType。寫在最后的原因是,避免報錯時,響應(yīng) contentType 已經(jīng)被修改了

    }
 }

到此這篇關(guān)于Java如何根據(jù)word模板導(dǎo)出數(shù)據(jù)的文章就介紹到這了,更多相關(guān)Java根據(jù)word模板導(dǎo)出數(shù)據(jù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java Swing GridBagLayout網(wǎng)格袋布局的實現(xiàn)

    Java Swing GridBagLayout網(wǎng)格袋布局的實現(xiàn)

    這篇文章主要介紹了Java Swing GridBagLayout網(wǎng)格袋布局的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-12-12
  • 如何使用nexus在局域網(wǎng)內(nèi)搭建maven私服及idea的使用

    如何使用nexus在局域網(wǎng)內(nèi)搭建maven私服及idea的使用

    這篇文章主要介紹了如何使用nexus在局域網(wǎng)內(nèi)搭建maven私服及idea的使用,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-11-11
  • Spring Boot 項目中使用Swagger2的示例

    Spring Boot 項目中使用Swagger2的示例

    本篇文章主要介紹了Spring Boot 項目中使用Swagger2的示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-01-01
  • Redis緩存及熱點key問題解決方案

    Redis緩存及熱點key問題解決方案

    這篇文章主要介紹了Redis緩存及熱點key問題解決方案,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-04-04
  • java實現(xiàn)順時針打印矩陣

    java實現(xiàn)順時針打印矩陣

    這篇文章主要為大家詳細(xì)介紹了java實現(xiàn)順時針打印矩陣的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-03-03
  • SpringCloud Feign轉(zhuǎn)發(fā)請求頭(防止session失效)的解決方案

    SpringCloud Feign轉(zhuǎn)發(fā)請求頭(防止session失效)的解決方案

    這篇文章主要介紹了SpringCloud Feign轉(zhuǎn)發(fā)請求頭(防止session失效)的解決方案,本文給大家分享兩種解決方案供大家參考,感興趣的朋友跟隨小編一起看看吧
    2020-10-10
  • Java動態(tài)加載類示例詳解

    Java動態(tài)加載類示例詳解

    這篇文章主要給大家介紹了關(guān)于Java動態(tài)加載類的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-02-02
  • 創(chuàng)建SpringBoot項目的全過程

    創(chuàng)建SpringBoot項目的全過程

    文章介紹了如何在IDEA專業(yè)版中創(chuàng)建SpringBoot項目,并通過一個簡單的示例展示了如何使用SpringBoot輸出"hello,Springboot"
    2025-03-03
  • Spring Boot FeignClient 如何捕獲業(yè)務(wù)異常信息

    Spring Boot FeignClient 如何捕獲業(yè)務(wù)異常信息

    這篇文章主要介紹了Spring Boot FeignClient 如何捕獲業(yè)務(wù)異常信息的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-06-06
  • 解決eclipse中console控制選項不見了的方法

    解決eclipse中console控制選項不見了的方法

    eclipse是一款用于編譯java語言的程序,利用這款軟件我們可以制作很多有趣的小程序,也可以制作一些大型的軟件項目,有的用戶在使用eclipse的時候會遇到console消失的情況,所以本文給大家介紹了解決eclipse中console控制選項不見了的方法,需要的朋友可以參考下
    2024-03-03

最新評論