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 文件名称 * @para编程客栈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模板导出数据
模板文件:
模板描述:{{?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模板导出数据内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!
精彩评论