有很多人會選擇用POI來實現這個功能,雖然說POI第三方包提供了很多方法,但JAVA IO流也不是吃素的,同樣也可以實現基於模板文件替換字符生成文檔.
這個功能在web應用中還是蠻常見的,用戶們喜歡根據自己的模板,然後在加上提供的內容,自動生成出不同的word文檔,省時省力.現在直接貼出代碼.
public class WangTest {
public static void main(String[] args) {
String templateContent = null;
String filePath = "D:/newWorkSpace20160516/SCPT/WebRoot/template/wangtest.mht";//模版文件
File file = new File(filePath);
if (!file.exists() || file.isDirectory()) {
}
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);// 用來存裝讀取到的內容
byte[] temp = new byte[1024];
int size = 0;
try {
while ((size = in.read(temp)) != -1) {
baos.write(temp, 0, size);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
templateContent = baos.toString();
String content = templateContent;
/**
* 直接使用String的replace直接替換文檔中的佔位符,這裏寫死,同樣可以以參數形式傳入
*/
content = content.replace("${name}", "wangzaogen" + "");
content = content.replace("${sex}", "男" + "");
content = content.replace("${age}", "20" + "");
File wordFile = new File(
"D:/newWorkSpace20160516/SCPT/WebRoot/template/+" + 2018
+ "wangtest.doc");//轉換後的word文檔
FileWriter fileWriter;
try {
fileWriter = new FileWriter(wordFile, true);
fileWriter.write(content);
fileWriter.close();
} catch (IOException e) {
}
}
}
這裏的模板文件是以.mht結尾的文件,不要大驚小怪的,這是由word文檔另存爲的網頁文件
簡單的模板內容如下圖:
執行main方法後轉換的word文檔後:
很簡單的一段代碼,不用引用第三方的jar包即可實現這個功能.