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 臨時文件存放地址 * @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),文中通過示例代碼介紹的非常詳細(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的使用,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-11-11SpringCloud Feign轉(zhuǎn)發(fā)請求頭(防止session失效)的解決方案
這篇文章主要介紹了SpringCloud Feign轉(zhuǎn)發(fā)請求頭(防止session失效)的解決方案,本文給大家分享兩種解決方案供大家參考,感興趣的朋友跟隨小編一起看看吧2020-10-10Spring Boot FeignClient 如何捕獲業(yè)務(wù)異常信息
這篇文章主要介紹了Spring Boot FeignClient 如何捕獲業(yè)務(wù)異常信息的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06