生活随笔
收集整理的這篇文章主要介紹了
用freemarker生成word模板
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
需求:
給文書統一生成一個搞頭文件,文件內容基本是一樣的。
用freemarker生成docx文檔
一、生成一個docx結尾的word模板,然后把文檔的后綴docx改成zip,zip里會有生成很多文件。如下圖:
然后打開word文件夾,如下圖:
把document.xml拿出來,把后綴xml改成ftl,然后把里面的內容(在線格式化xml)格式化一下,把一些可變的參數做成變量。
二、在resources文件夾下創建wordTemplates文件夾,里面放剛才的zip和改名的gtwj.ftl文件。
三、替換word模板類:
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.io.*;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;public class ZipUtils {private static final Logger logger = LoggerFactory.getLogger(ZipUtils.class);/*** 替換document , header1** @param zipInputStream zip文件的zip輸入流* @param zipOutputStream 輸出的zip輸出流* @param bodyOs 要替換的 word內容流*/public static void replaceItem(ZipInputStream zipInputStream, ZipOutputStream zipOutputStream,ByteArrayOutputStream bodyOs) {String bodyname = "word/document.xml";//if (null == zipInputStream || null == zipOutputStream || null == bodyOs ) {return;}ZipEntry entryIn;try {while ((entryIn = zipInputStream.getNextEntry()) != null) {String entryName = entryIn.getName();ZipEntry entryOut = new ZipEntry(entryName);// 只使用 namezipOutputStream.putNextEntry(entryOut);if (entryName.equals(bodyname)) {// 使用替換流 替換word內容byte[] buf = bodyOs.toByteArray();zipOutputStream.write(buf,0,buf.length);}else {// 緩沖區byte[] buf = new byte[8 * 1024];int len;// 輸出普通Zip流while ((len = (zipInputStream.read(buf))) > 0) {zipOutputStream.write(buf, 0, len);}}// 關閉此 entryzipOutputStream.closeEntry();}} catch (IOException e) {logger.error("zip文件的zip輸入流失敗:", e);} finally {close(bodyOs);close(zipInputStream);close(zipOutputStream);}}/*** 包裝輸入流*/public static ZipInputStream wrapZipInputStream(InputStream inputStream) {ZipInputStream zipInputStream = new ZipInputStream(inputStream);return zipInputStream;}/*** 包裝輸出流*/public static ZipOutputStream wrapZipOutputStream(OutputStream outputStream) {ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);return zipOutputStream;}private static void close(InputStream inputStream) {if (null != inputStream) {try {inputStream.close();} catch (IOException e) {logger.error("關閉流失敗:", e);}}}private static void close(OutputStream outputStream) {if (null != outputStream) {try {outputStream.flush();outputStream.close();} catch (IOException e) {logger.error("關閉流失敗:", e);}}}/*** 獲取絕對路徑* @return*/public static String systemUrl(){if(System.getProperties().getProperty("os.name").toUpperCase().indexOf("WINDOWS") != -1){return "D:";}return "/temp";}public static void wordAndDoc(Map<String, Object> dataMap,ByteArrayOutputStream byteArrayOutputStream) throws IOException {//word bodyString bodyName = "gtwjtest.ftl";ByteArrayOutputStream bodyOs = writeFile(bodyName,dataMap);ZipInputStream zipInputStream = ZipUtils.wrapZipInputStream(ZipUtils.class.getResourceAsStream("/wordTemplates/gtwj.zip"));ZipOutputStream zipOutputStream = ZipUtils.wrapZipOutputStream(byteArrayOutputStream);ZipUtils.replaceItem(zipInputStream, zipOutputStream, bodyOs);}public static void word(Map<String, Object> dataMap,ByteArrayOutputStream byteArrayOutputStream) throws IOException {//word bodyString bodyName = "gtwj.ftl";ByteArrayOutputStream bodyOs = writeFile(bodyName,dataMap);ZipInputStream zipInputStream = ZipUtils.wrapZipInputStream(ZipUtils.class.getResourceAsStream("/wordTemplates/gtwj.zip"));ZipOutputStream zipOutputStream = ZipUtils.wrapZipOutputStream(byteArrayOutputStream);ZipUtils.replaceItem(zipInputStream, zipOutputStream, bodyOs);}public static String wordFile(Map<String, Object> dataMap,String docxUrl) throws IOException {String bodyName = "gtwj.ftl";ByteArrayOutputStream bodyOs = writeFile(bodyName,dataMap);ZipInputStream zipInputStream = ZipUtils.wrapZipInputStream(ZipUtils.class.getResourceAsStream("/wordTemplates/gtwj.zip")); //D:\zip\月度用電報告.zipZipOutputStream zipOutputStream = ZipUtils.wrapZipOutputStream(new FileOutputStream(new File(docxUrl)));ZipUtils.replaceItem(zipInputStream, zipOutputStream, bodyOs);return docxUrl;}/*** @Description 生成帶數據的模板* @Param*/public static ByteArrayOutputStream writeFile(String templateName,Map<String, Object> dataMap) throws IOException {Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);configuration.setClassForTemplateLoading(ZipUtils.class, "/wordTemplates/");Template template = configuration.getTemplate(templateName);ByteArrayOutputStream os = new ByteArrayOutputStream();Writer out = new BufferedWriter(new OutputStreamWriter(os),10240);try {template.process(dataMap,out);} catch (TemplateException e) {logger.error("生成帶數據的模板失敗:", e);}finally {if(out != null ){out.close();}}return os;}/*** @Description 生成帶數據的模板* @Param*/public static void writeFile(String outFilePath,String templateName,Map<String, Object> dataMap) throws IOException {Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);configuration.setClassForTemplateLoading(ZipUtils.class, "/ftl");Template template = configuration.getTemplate(templateName);File docFile = new File(outFilePath);FileOutputStream fos = new FileOutputStream(docFile);Writer out = new BufferedWriter(new OutputStreamWriter(fos),10240);try {template.process(dataMap,out);} catch (TemplateException e) {logger.error("生成帶數據的模板失敗:", e);}finally {if(out != null ){out.close();}}}/*** @Description 判斷文件夾是否存在 不存在就創建* @Param:* @return:*/private static void isChartPathExist(String dirPath) {File file = new File(dirPath);if (!file.exists()) {file.mkdirs();}System.out.println(file.exists()+" dirPath "+dirPath);}public static void main(String[] args) {
// String templatePath =ZipUtils.class.getResource("/").getPath()+ "/ftl";
// System.out.println(templatePath);
// isChartPathExist("D:\\zip\\123");File file = new File("F:\\word\\gtwj.pdf");if(file.exists()){if(file.isFile()){boolean b = file.delete();if (b) {logger.info("成功");}}}}
}
四、項目里引入jar包如下:
<dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId><version>2.3.28</version></dependency>
五、我用到的方法 ZipUtils.word(map, byteArrayOutputStream);其中map就是變量。
總結
以上是生活随笔為你收集整理的用freemarker生成word模板的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。