Java模板動態生成word文件的方法步驟
最近項目中需要根據模板生成word文檔,模板文件也是word文檔。當時思考一下想用POI API來做,但是覺得用起來相對復雜。后來又找了一種方式,使用freemarker模板生成word文件,經過嘗試覺得還是相對簡單易行的。
使用freemarker模板生成word文檔主要有這么幾個步驟
1、創建word模板:因為我項目中用到的模板本身是word,所以我就直接編輯word文檔轉成freemarker(.ftl)格式的。
2、將改word文件另存為xml格式,注意使用另存為,不是直接修改擴展名。
3、將xml文件的擴展名改為ftl
4、編寫java代碼完成導出
使用到的jar:freemarker.jar (2.3.28) ,其中Configuration對象不推薦直接new Configuration(),仔細看Configuration.class文件會發現,推薦的是 Configuration(Version incompatibleImprovements) 這個構造方法,具體這個構造方法里面傳的就是Version版本類,而且版本號不能低于2.3.0
閑言碎語不再講,直接上代碼
public static void exportDoc() {String picturePath = 'D:/image.png';Map<String, Object> dataMap = new HashMap<String, Object>();dataMap.put('brand', '海爾');dataMap.put('store_name', '海爾天津');dataMap.put('user_name', '小明');//經過編碼后的圖片路徑String image = getWatermarkImage(picturePath);dataMap.put('image', image);//Configuration用于讀取ftl文件Configuration configuration = new Configuration(new Version('2.3.0'));configuration.setDefaultEncoding('utf-8');Writer out = null;try { //輸出文檔路徑及名稱 File outFile = new File('D:/導出優惠證明.doc'); out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File('outFile')), 'utf-8'), 10240);} catch (UnsupportedEncodingException e) { e.printStackTrace();} catch (FileNotFoundException e) { e.printStackTrace();}// 加載文檔模板Template template = null;try { //指定路徑,例如C:/a.ftl 注意:此處指定ftl文件所在目錄的路徑,而不是ftl文件的路徑 configuration.setDirectoryForTemplateLoading(new File('C:/')); //以utf-8的編碼格式讀取文件 template = configuration.getTemplate('導出優惠證明.ftl', 'utf-8');} catch (IOException e) { e.printStackTrace(); throw new RuntimeException('文件模板加載失敗!', e);}// 填充數據try { template.process(dataMap, out);} catch (TemplateException e) { e.printStackTrace(); throw new RuntimeException('模板數據填充異常!', e);} catch (IOException e) { e.printStackTrace(); throw new RuntimeException('模板數據填充異常!', e);} finally { if (null != out) {try { out.close();} catch (IOException e) { e.printStackTrace(); throw new RuntimeException('文件輸出流關閉異常!', e);} }} }
因為很多時候我們根據模板生成文件需要添加水印,也就是插入圖片
/*** * 處理圖片 * @param watermarkPath 圖片路徑 D:/image.png * @return */private String getWatermarkImage(String watermarkPath) { InputStream in = null; byte[] data = null; try {in = new FileInputStream(watermarkPath);data = new byte[in.available()];in.read(data);in.close(); } catch (Exception e) {e.printStackTrace(); } BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(data);}
注意點:
插入圖片后的word轉化為ftl模板文件(ps:水印圖片可以在word上調整到自己想要的大小,然后在執行下面的步驟)
1、先另存為xml
2、將xml擴展名改為ftl
3、打開ftl文件, 搜索w:binData 或者 png可以快速定位圖片的位置,圖片 已經編碼成0-Z的字符串了, 如下:
5、 將上述0-Z的字符串全部刪掉,寫上${image}(變量名隨便寫,跟dataMap里的key保持一致)后保存
6、也是創建一個Map, 將數據存到map中,只不過我們要把圖片用代碼進行編碼,將其也編成0-Z的字符串,代碼請看上邊
至此一個簡單的按照模板生成word并插入圖片(水印)功能基本完成。
到此這篇關于Java模板動態生成word文件的方法步驟的文章就介紹到這了,更多相關Java 模板動態生成word內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
