用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);
// 只使用 name
zipOutputStream.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);
}
}
// 關閉此 entry
zipOutputStream.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 body
String 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 body
String 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\月度用電報告.zip
ZipOutputStream 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 模板生成Excel和Word文件
使用freemarker 模板生成文件Excel和Word文件 freemarker的常用語法 1. 引入依賴的包 pom.xml文件 2. Freemarker配置 FreemarkerUtil.java 3. ftl模板文件的生成 在excel/word文件里畫好模板,將excel/word文件另存為.xml文件。在template文件夾下新建模板文件,后綴為.ftl,然后將.xml文件的內容...
freemarker 生成word
freemarker 生成word 新公司給了我一個任務,生成word,模板用freemarker,剛好又學了個新東西 1,導freemarker jar包 公司項目沒用啥框架,也沒用maven 用jar包導入的 maven依賴 2,準備好flt后綴模板 2.1 準備word模板 根據需求設置不同的值 ${String} 2.2 另存為xml文件 2.3 修改xml后綴為ftl 3,word生成工...
用freemarker生成word文檔,并插入圖片
用freemarker生成word文檔,并插入圖片 最近需要做一個問卷功能,要求用戶填寫完問卷后,后臺會生成一個word文檔,將用戶提交的數據插入到word中。 創建word模板 新建一個word文檔,將需要應用的格式固定好 修改好格式后,將word文檔保存為XML格式的文件 例: 將word保存為xml格式 將XML中base64格式的圖片信息刪除掉,改為占位符,如:${image} 如果需要在...
python 用word模板自動生成報告
不啰嗦,直接進入正題,先放上結果: 利用下面的模板自動生成報告篇: 注:后面會詳細講解如何生成模板。 如何生成模板: 新建一個 docx 文件。 2.代碼部分 好了以上,完成。...
使用FreeMarker模板導出word
1.目標:需要導出的word內容如圖,其中部分數據是需要程序動態填充的 2.將上述文檔另存為xml格式,然后用notepad++(到官網下載,保證能正常安裝xml tools插件)打開 3.打開的xml文件會如下顯示,需要格式化 4. 為notepad++安裝格式化工具插件xml tools 1)點擊notepad++的菜單“插件”,接著點擊選項“插件管理&rd...
猜你喜歡
freemarker + ItextRender 根據模板生成PDF文件
1. 制作模板 2. 獲取模板,并將所獲取的數據加載生成html文件 2. 生成PDF文件 其中由兩個地方需要注意,都是關于獲取文件路徑的問題,由于項目部署的時候是打包成jar包形式,所以在開發過程中時直接安照傳統的獲取方法沒有一點文件,但是當打包后部署,總是出錯。于是參考網上文章,先將文件讀出來到項目的臨時目錄下,然后再按正常方式加載該臨時文件; 還有一個問題至今沒有解決,就是關于生成PDF文件...
電腦空間不夠了?教你一個小秒招快速清理 Docker 占用的磁盤空間!
Docker 很占用空間,每當我們運行容器、拉取鏡像、部署應用、構建自己的鏡像時,我們的磁盤空間會被大量占用。 如果你也被這個問題所困擾,咱們就一起看一下 Docker 是如何使用磁盤空間的,以及如何回收。 docker 占用的空間可以通過下面的命令查看: TYPE 列出了docker 使用磁盤的 4 種類型: Images:所有鏡像占用的空間,包括拉取下來的鏡像,和本地構建的。 Con...
requests實現全自動PPT模板
http://www.1ppt.com/moban/ 可以免費的下載PPT模板,當然如果要人工一個個下,還是挺麻煩的,我們可以利用requests輕松下載 訪問這個主頁,我們可以看到下面的樣式 點每一個PPT模板的圖片,我們可以進入到詳細的信息頁面,翻到下面,我們可以看到對應的下載地址 點擊這個下載的按鈕,我們便可以下載對應的PPT壓縮包 那我們就開始做吧 首先,查看網頁的源代碼,我們可以看到每一...