1. 程式人生 > >Java使用POI匯出Word文件

Java使用POI匯出Word文件

package com.iflytek.chy;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
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 App {
private static String regex = "[a-zA-Z]+";
private static Pattern pattern = Pattern.compile(regex);
public static void main(String[] args) throws IOException {
Map<String, String> map = new HashMap<String, String>();
map.put("qbdj", "你好");
map.put("zlhtbt", "姓名");
map.put("fwqh", "性別");
map.put("qbly", "年齡");
map.put("lrsj", "生日");
map.put("bt", "職業");
map.put("xxzw", "工作城市");
map.put("bb", "武漢光谷");
map.put("ss", "武漢光谷");
map.put("ff", "武漢光谷");
map.put("gg", "武漢光谷");
map.put("hh", "武漢光谷");
map.put("dd", "武漢光谷");
String filePath = "D:\\java_workspace_qbNew\\qb-yp\\qb-xsfx\\target\\classes\\config\\template\\SWSJ-test.docx";
InputStream is = new FileInputStream(filePath);
@SuppressWarnings("resource")
XWPFDocument doc = new XWPFDocument(is);
List<XWPFParagraph> list = doc.getParagraphs();
// 替換佔位符
for (int i = 0; i < list.size(); i++) {
XWPFParagraph xwpfParagraph = list.get(i);
List<XWPFRun> runs = xwpfParagraph.getRuns();
if (runs != null && runs.size() > 0) {
for (int j = runs.size() - 1; j >= 0; j--) {
if (map.containsKey(runs.get(j).text())) {
System.out.println("run:" + runs.get(j).text());
runs.get(j).setText(map.get(runs.get(j).text()), 0);
}
}
}
}
// 替換表格中的佔位符
List<XWPFTable> tables = doc.getTables();
for (XWPFTable xwpfTable : tables) {
for (int i = 0; i < xwpfTable.getNumberOfRows(); i++) {
XWPFTableRow row = xwpfTable.getRow(i);
List<XWPFTableCell> tableCells = row.getTableCells();
for (XWPFTableCell xwpfTableCell : tableCells) {
List<XWPFParagraph> paragraphs = xwpfTableCell.getParagraphs();
for (XWPFParagraph xwpfParagraph : paragraphs) {
List<XWPFRun> runs = xwpfParagraph.getRuns();
for (XWPFRun xwpfRun : runs) {
String trim = xwpfRun.text();
Matcher matcher = pattern.matcher(trim);
String temp = "";
while (matcher.find()) {
temp = matcher.group();
}
if (StringUtils.isNotBlank(temp)) {
trim = trim.replace(temp, map.get(temp));
}
xwpfRun.setText(trim, 0);
}
}
}
}
}
OutputStream os = new FileOutputStream(
"D:\\\\java_workspace_qbNew\\\\qb-yp\\\\qb-xsfx\\\\target\\\\classes\\\\config\\\\template\\\\MY-SWSJ-test.docx");
doc.write(os);
os.close();
is.close();
}
}