Java-web利用模板檔案實現匯出自定義word文件
阿新 • • 發佈:2018-12-10
由於專案開發需要,產品給出word模板,需要匯出該格式的word檔案。
1.通過word模板檔案生成我們需要的模板.ftl檔案。
步驟:將word檔案轉換成Microsoft XML格式檔案(開啟word,檔案另存為xml格式檔案),用notepad++編輯器開啟檔案,修改檔案裡面的內容,具體資料用${引數}替換,全部替換完成以後,將檔案的字尾名改成.ftl,檔案格式。
2.將生成好的檔案放到專案相應的目錄下,便於後面讀取使用。
3.後臺實現邏輯:
try { Map<String, Object> resultMap = new HashMap<String, Object>(); resultMap.put("title", "測試"); resultMap.put("keyword", "匯出word"); // 生成Word文件 File file = WordGenerator.createDoc(resultMap, "template"); InputStream fin = new FileInputStream(file); response.setCharacterEncoding("utf-8"); response.setContentType("application/msword"); // 設定瀏覽器以下載的方式處理該檔案 response.addHeader("Content-Disposition", "attachment;filename=" + "\"" + new String(fileName.getBytes(), "iso-8859-1") + ".doc"); ServletOutputStream out = response.getOutputStream(); // 緩衝區 byte[] buffer = new byte[512]; int bytesToRead = -1; while ((bytesToRead = fin.read(buffer)) != -1) { out.write(buffer, 0, bytesToRead); } out.flush(); if (fin != null) { fin.close(); } if (out != null) { out.close(); } if (file != null) { // 刪除臨時檔案 file.delete(); } } catch (Exception e) { e.printStackTrace(); }
createDoc方法:通過模板和輸入資料dataMap,生成臨時word檔案,再通過瀏覽器下載該檔案。
public static File createDoc(Map<?, ?> dataMap, String type) { // 臨時檔名稱 String name = "temp" + (int) (Math.random() * 100000) + ".doc"; // 臨時檔案儲存路徑 String tempFileDir = PropertiesUtil.getValueByKey("path");//臨時檔案儲存路徑 File fileMkDir = new File(tempFileDir); // 如果資料夾不存在則建立 if (!fileMkDir.exists() && !fileMkDir.isDirectory()) { fileMkDir.mkdir(); } File file = new File(tempFileDir, name); // 獲取模板 Template template = allTemplates.get(type); try { Writer out = null; FileOutputStream fos = null; fos = new FileOutputStream(file); OutputStreamWriter writer = new OutputStreamWriter(fos, "UTF-8"); out = new BufferedWriter(writer); template.process(dataMap, out); out.flush(); out.close(); } catch (Exception ex) { ex.printStackTrace(); throw new RuntimeException(ex); } return file; }
模板初始化:
private static Configuration configuration = null; private static Map<String, Template> allTemplates = null; static { configuration = new Configuration(); configuration.setDefaultEncoding("utf-8"); configuration.setClassForTemplateLoading(WordGenerator.class, "/download"); allTemplates = new HashMap<String, Template>(); try { Template template = configuration.getTemplate("template.ftl","UTF-8"); Template template1 = configuration.getTemplate("template1.ftl", "UTF-8"); Template template2 = configuration.getTemplate("template1.ftl", "UTF-8"); allTemplates.put("template", template); allTemplates.put("template1", template1); allTemplates.put("template2",template2); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } }
本方法是基於任意word模板實現相應匯出的實現模式,因此較直接匯出word相對來說複雜一點,但是能滿足任意匯出樣式。