介紹一個(gè)使用word模板生成word的方法,同樣是通過(guò)替換模板中的變量來(lái)達(dá)成目的,使用POI。
Word模板如下:
word模板
具體實(shí)現(xiàn)步驟如下:
- 創(chuàng)建XwpfTUtil工具類,詳細(xì)代碼見(jiàn)文末。
- 在實(shí)現(xiàn)方法中創(chuàng)建XwpfTUtil實(shí)例
XwpfTUtil xwpfUtil = new XwpfTUtil();
- 創(chuàng)建輸入流和XWPFDocument實(shí)例
InputStream is = new FileInputStream(“Word模板路徑”);
XWPFDocument doc = new XWPFDocument(is);
- 替換模板中的變量,doc為XWPFDocument實(shí)例,map里存放著要替換的值
xwpfTUtil.replaceInPara(doc, map);
xwpfTUtil.replaceInTable(doc, map);
- 創(chuàng)建輸出流并生成Word,關(guān)閉各個(gè)流
OutputStream os =response.outputStream;(web應(yīng)用中可以這樣)
doc.write(os);
xwpfTUtil.close(os)
xwpfTUtil.close(is);
os.flush();
os.close();
至此,Word就生成了。
XwpfTUtil的源碼見(jiàn)下:
public class XwpfTUtil {
/**
* 替換段落里面的變量
* @param doc 要替換的文檔
* @param params 參數(shù)
*/
public voidreplaceInPara(XWPFDocument doc, Map<String, Object> params) {
Iterator<XWPFParagraph> iterator = doc.getParagraphsIterator();
XWPFParagraph para;
while(iterator.hasNext()) {
para =iterator.next();
this.replaceInPara(para, params);
}
}
/**
* 替換段落里面的變量
* @param para 要替換的段落
* @param params 參數(shù)
*/
public voidreplaceInPara(XWPFParagraph para, Map<String, Object> params) {
List<XWPFRun>runs;
Matcher matcher;
if (this.matcher(para.getParagraphText()).find()){
runs =para.getRuns();
int start = -1;
int end = -1;
String str ="";
for (int i = 0; i< runs.size(); i++) {
XWPFRun run =runs.get(i);
String runText = run.toString();
if ('$' ==runText.charAt(0)&&'{' == runText.charAt(1)) {
start = i;
}
if ((start !=-1)) {
str +=runText;
}
if ('}' ==runText.charAt(runText.length() - 1)) {
if (start!= -1) {
end =i;
break;
}
}
}
for (int i =start; i <= end; i++) {
para.removeRun(i);
i--;
end--;
}
for (String key :params.keySet()) {
if (str.equals(key)){
para.createRun().setText((String) params.get(key));
break;
}
}
}
}
/**
* 替換表格里面的變量
* @param doc 要替換的文檔
* @param params 參數(shù)
*/
public voidreplaceInTable(XWPFDocument doc, Map<String, Object> params) {
Iterator<XWPFTable> iterator = doc.getTablesIterator();
XWPFTable table;
List<XWPFTableRow> rows;
List<XWPFTableCell> cells;
List<XWPFParagraph>paras;
while(iterator.hasNext()) {
table =iterator.next();
rows =table.getRows();
for (XWPFTableRowrow : rows) {
cells =row.getTableCells();
for(XWPFTableCell cell : cells) {
paras =cell.getParagraphs();
for(XWPFParagraph para : paras) {
this.replaceInPara(para, params);
}
}
}
}
}
/**
* 正則匹配字符串
* @param str
* @return
*/
private Matchermatcher(String str) {
Pattern pattern =Pattern.compile("\\$\\{(.+?)\\}", Pattern.CASE_INSENSITIVE);
Matcher matcher =pattern.matcher(str);
return matcher;
}
/**
* 關(guān)閉輸入流
* @param is
*/
public voidclose(InputStream is) {
if (is != null) {
try {
is.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
/**
* 關(guān)閉輸出流
* @param os
*/
public voidclose(OutputStream os) {
if (os != null) {
try {
os.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
}