java freemarker動態替換word文件中佔位符
阿新 • • 發佈:2022-04-21
1.使用map替換
public static void createWord(Map<String,Object> dataMap, String templateName, ByteArrayOutputStream outputStream){ try { //建立配置例項 Configuration configuration = new Configuration(); //設定編碼 configuration.setDefaultEncoding("UTF-8"); //設定編碼configuration.setDefaultEncoding("UTF-8"); File exportTemplate = ResourceFinder.getResources("exportTemplate")[0].getFile(); configuration.setDirectoryForTemplateLoading(exportTemplate);// 本地模板路徑 //獲取模板 Template template = configuration.getTemplate(templateName); Writer out= new OutputStreamWriter(outputStream); //生成檔案 template.process(dataMap, out); //關閉流 out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } }
2.使用
public void exportDutyLog(String ownerId, LocalDate date, HttpServletResponse response) throwsIOException { String fileName = "值班日誌-".concat(date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))).concat(".docx"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); HashMap<String, Object> stringMaps = Maps.newHashMap(); try { process(ownerId, date, stringMaps); } catch(Exception e) { e.printStackTrace(); } createWord(stringMaps,"dutylog.ftl",outputStream); response.setCharacterEncoding("utf-8"); // 設定編碼格式 response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8")); ServletOutputStream servletOutputStream = response.getOutputStream(); servletOutputStream.write(outputStream.toByteArray()); }
3.使用時需要將word匯出為xml,修改錯亂的佔位符位置,方法呼叫即可成功
4.依賴
compile group: 'org.freemarker', name: 'freemarker', version: '2.3.28'TRANSLATE with x English TRANSLATE with EMBED THE SNIPPET BELOW IN YOUR SITE Enable collaborative features and customize widget: Bing Webmaster Portal Back