就整理一下
(docx 的 lib 比 doc 的好很多,doc比半殘還可憐orz...後來直接放棄,就只用docx就好)
建立 docx,寫出檔案
FileInputStream fis = new FileInputStream(templateFile); XWPFDocument docx = new XWPFDocument(fis); //... do something what u want FileOutputStream out = new FileOutputStream(outFile); docx.write(out);
如果不用讀 template 的話,就是直接 new XWPFDocument()
最基本的找內文取代文字
前者是找 平 的內容
後者是找 table 內符合的內容
for (XWPFParagraph p : docx.getParagraphs()) {
List<XWPFRun> runs = p.getRuns();
if (runs != null) {
for (XWPFRun r : runs) {
String text = r.getText(0);
if (text != null && text.indexOf(param.getFind()) >= 0 ) {
text = StringUtils.replace(text, param.getFind(), param.getReplace());
r.setText(text, 0);
}
}
}
}
for (XWPFTable tbl : docx.getTables()) {
for (XWPFTableRow row : tbl.getRows()) {
for (XWPFTableCell cell : row.getTableCells()) {
for (XWPFParagraph p : cell.getParagraphs()) {
for (XWPFRun r : p.getRuns()) {
String text = r.getText(0);
if (text != null && text.indexOf(param.getFind()) >= 0) {
text = StringUtils.replace(text, param.getFind(), param.getReplace());
r.setText(text, 0);
}
}
}
}
}
}
沒有留言:
張貼留言