Java如何根據(jù)word模板導(dǎo)出數(shù)據(jù)
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 臨時(shí)文件存放地址
* @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");
}
//防止文件過(guò)大,報(bào)錯(cuò):java.io.IOException: Zip bomb detected! The file would exceed the max
ZipSecureFile.setMinInflateRatio(-1.0d);
//開(kāi)始導(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);
}
}
/**
* 刪除臨時(shí)生成的文件
*/
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ù)效果:

方法補(bǔ)充
java實(shí)現(xiàn)根據(jù)word模板導(dǎo)出數(shù)據(jù)
模板文件:

模板描述:{{?govinspectItemVOList}} 為循環(huán)遍歷的數(shù)據(jù)實(shí)體
代碼塊:
//生成文件所在路徑
String dirName = System.getProperty("user.dir") + File.separator + "file";
//模板文件存放地址
String templateFileName = dirName + File.separator + "質(zhì)量安全巡查檢查報(bào)告.docx";
//生成的臨時(shí)文件
String fileName = "質(zhì)量安全巡查檢查報(bào)告" + 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");
//刪除臨時(shí)文件
outputFile.delete();
}
// 設(shè)置 header 和 contentType。寫(xiě)在最后的原因是,避免報(bào)錯(cuò)時(shí),響應(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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java Swing GridBagLayout網(wǎng)格袋布局的實(shí)現(xiàn)
這篇文章主要介紹了Java Swing GridBagLayout網(wǎng)格袋布局的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12
如何使用nexus在局域網(wǎng)內(nèi)搭建maven私服及idea的使用
這篇文章主要介紹了如何使用nexus在局域網(wǎng)內(nèi)搭建maven私服及idea的使用,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-11-11
Spring Boot 項(xiàng)目中使用Swagger2的示例
本篇文章主要介紹了Spring Boot 項(xiàng)目中使用Swagger2的示例,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-01-01
Redis緩存及熱點(diǎn)key問(wèn)題解決方案
這篇文章主要介紹了Redis緩存及熱點(diǎn)key問(wèn)題解決方案,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-04-04
SpringCloud Feign轉(zhuǎn)發(fā)請(qǐng)求頭(防止session失效)的解決方案
這篇文章主要介紹了SpringCloud Feign轉(zhuǎn)發(fā)請(qǐng)求頭(防止session失效)的解決方案,本文給大家分享兩種解決方案供大家參考,感興趣的朋友跟隨小編一起看看吧2020-10-10
創(chuàng)建SpringBoot項(xiàng)目的全過(guò)程
文章介紹了如何在IDEA專業(yè)版中創(chuàng)建SpringBoot項(xiàng)目,并通過(guò)一個(gè)簡(jiǎn)單的示例展示了如何使用SpringBoot輸出"hello,Springboot"2025-03-03
Spring Boot FeignClient 如何捕獲業(yè)務(wù)異常信息
這篇文章主要介紹了Spring Boot FeignClient 如何捕獲業(yè)務(wù)異常信息的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06
解決eclipse中console控制選項(xiàng)不見(jiàn)了的方法
eclipse是一款用于編譯java語(yǔ)言的程序,利用這款軟件我們可以制作很多有趣的小程序,也可以制作一些大型的軟件項(xiàng)目,有的用戶在使用eclipse的時(shí)候會(huì)遇到console消失的情況,所以本文給大家介紹了解決eclipse中console控制選項(xiàng)不見(jiàn)了的方法,需要的朋友可以參考下2024-03-03

