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 cn.afterturn.easypoi.word.WordExportUtil; import org.apache.poi.xwpf.usermodel.XWPFDocument; public class WordUtil { /** * EasyPoi 替换数据 导出 word * @param templatePath word模板地址 * @param tempDir 临时文件存放地址 * @param filename 文件名称 * @param 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"); } 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(); } }
上面这个工具类是网上找的,代码ok。
接下来是数据封装。
接下来就是模板上填写内容了。