Word 2007 POI 替換文件內容
最近專案中需要替換Word模版中的變數,本來打算用書籤做的,後來發現POI的bookmark不具有設定標籤內容的功能。如果採用getText(),則會丟失樣式。
模版截圖為
分為頁首、頁尾、中間內容。
處理程式碼如下。
package cn.com.ebidding.word.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
public class WordReplaceUtil {
public static Map<String, String> params = new HashMap<String, String>();
public static void main(String[] args) {
String readPath = "awardNotice.docx";
String writePath = "fool.doc";
initParams();
try {
XWPFDocument doc = generateWord(params,readPath);
replaceFooterAndHeader(doc);
doc.write(new FileOutputStream(new File(writePath)));
} catch (Exception e) {
System.out.println("Error");
e.printStackTrace();
}
System.out.println("End");
}
//獲取檔案型別
public static String getFileSufix(String fileName){
int index = fileName.lastIndexOf(".");
return fileName.substring(index + 1);
}
//初始化替換資料
private static void initParams() {
params.put("${招標機構名稱}", "中國石油華北分公司北京集團");
params.put("${招標機構名稱英文}", "WCFGKEBS");
params.put("${型別}", "中標成功");
params.put("${通知書編號}", "0924");
params.put("${中標公司名稱}", "英偉達");
params.put("${專案名稱}", "處理器");
params.put("${標段名稱}", "CLQ01");
params.put("${專案編號}", "Apple01");
params.put("${標段編號}", "KL003");
params.put("${金額}", "13000");
params.put("${招標機構名稱", "易招標");
params.put("${招標公司名稱}", "德瑪西亞");
params.put("${日期}", DateFormat.getDateInstance().format(new Date()));
}
public static void replaceFooterAndHeader(XWPFDocument doc){
List<XWPFParagraph> footers = doc.getHeaderFooterPolicy().getDefaultFooter().getParagraphs();
List<XWPFParagraph> headers = doc.getHeaderFooterPolicy().getDefaultHeader().getParagraphs();
//處理頁尾
for (XWPFParagraph paragraph : footers) {
List<XWPFRun> runs = paragraph.getRuns();
for (XWPFRun run : runs) {
String text = run.getText(0);
if(StringUtils.isNotEmpty(text)){
for(Entry<String, String> entry : params.entrySet()){
String key = entry.getKey();
if(text.indexOf(key) != -1){
Object value = entry.getValue();
if(value instanceof String){
text = text.replace(key, value.toString());
run.setText(text,0);
}
}
}
}
}
}
//處理頁首
for (XWPFParagraph paragraph : headers) {
List<XWPFRun> runs = paragraph.getRuns();
for (XWPFRun run : runs) {
String text = run.getText(0);
if(StringUtils.isNotEmpty(text)){
for(Entry<String, String> entry : params.entrySet()){
String key = entry.getKey();
if(text.indexOf(key) != -1){
Object value = entry.getValue();
if(value instanceof String){
text = text.replace(key, value.toString());
run.setText(text,0);
}
}
}
}
}
}
}
public static XWPFDocument generateWord(Map<String, String> param, String filePath) {
XWPFDocument doc = null;
try {
OPCPackage pack = POIXMLDocument.openPackage(filePath);
doc = new XWPFDocument(pack);
if (param != null && param.size() > 0) {
// //處理段落
// List<XWPFParagraph> paragraphList = doc.getParagraphs();
// processParagraphs(paragraphList, param, doc);
//處理表格
Iterator<XWPFTable> it = doc.getTablesIterator();
while (it.hasNext()) {
XWPFTable table = it.next();
List<XWPFTableRow> rows = table.getRows();
for (XWPFTableRow row : rows) {
List<XWPFTableCell> cells = row.getTableCells();
for (XWPFTableCell cell : cells) {
List<XWPFParagraph> paragraphListTable = cell.getParagraphs();
processParagraphs(paragraphListTable, param, doc);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return doc;
}
public static void processParagraphs(List<XWPFParagraph> paragraphList,Map<String, String> param,XWPFDocument doc){
if(paragraphList != null && paragraphList.size() > 0){
for(XWPFParagraph paragraph:paragraphList){
List<XWPFRun> runs = paragraph.getRuns();
for (XWPFRun run : runs) {
String text = run.getText(0);
if(text != null){
for (Entry<String, String> entry : param.entrySet()) {
String key = entry.getKey();
if(text.indexOf(key) != -1){
Object value = entry.getValue();
if (value instanceof String) {//文字替換
text = text.replace(key, value.toString());
run.setText(text,0);
}
}
}
// if(isSetText){
// run.setText(text,0);
// }
}
}
}
}
}
}
依賴jar包
希望能給遇到同樣問題的人提供幫助。