java 使用POI 读写word 表格
发布时间:2020-05-24 15:43:28 所属栏目:Java 来源:互联网
导读:java 使用POI 读写word 表格
|
下面是脚本之家 jb51.cc 通过网络收集整理的代码片段。 脚本之家小编现在分享给大家,也给大家做个参考。 import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.hwpf.usermodel.Table;
import org.apache.poi.hwpf.usermodel.TableCell;
import org.apache.poi.hwpf.usermodel.TableIterator;
import org.apache.poi.hwpf.usermodel.TableRow;
public class POIWordUtil {
public static void main(String[] args) throws Exception {
Map<String,Text> replaces = new HashMap<String,Text>();
replaces.put("${username}",Text.str("rongzhi_li"));
replaces.put("${password}",Text.str("1123456"));
replaces.put("${author}",Text.str("lee"));
poiWordTableReplace("t1.doc","t2.doc",replaces);
}
public static void poiWordTableReplace(String sourceFile,String newFile,Map<String,Text> replaces) throws Exception {
FileInputStream in = new FileInputStream(sourceFile);
HWPFDocument hwpf = new HWPFDocument(in);
Range range = hwpf.getRange();// 得到文档的读取范围
TableIterator it = new TableIterator(range);
// 迭代文档中的表格
while (it.hasNext()) {
Table tb = (Table) it.next();
// 迭代行,默认从0开始
for (int i = 0; i < tb.numRows(); i++) {
TableRow tr = tb.getRow(i);
// 迭代列,默认从0开始
for (int j = 0; j < tr.numCells(); j++) {
TableCell td = tr.getCell(j);// 取得单元格
// 取得单元格的内容
for (int k = 0; k < td.numParagraphs(); k++) {
Paragraph para = td.getParagraph(k);
String s = para.text();
final String old = s;
for (String key : replaces.keySet()) {
if (s.contains(key)) {
s = s.replace(key,replaces.get(key).getText());
}
}
if (!old.equals(s)) {// 有变化
para.replaceText(old,s);
s = para.text();
System.out.println("old:" + old + "->" + "s:" + s);
}
} // end for
} // end for
} // end for
} // end while
FileOutputStream out = new FileOutputStream(newFile);
hwpf.write(out);
out.flush();
out.close();
}
}
public abstract class Text {
public abstract String getText();
public static Text str(final String string) {
return new Text() {
@Override
public String getText() {
return string;
}
};
}
}
以上是脚本之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。 如果觉得脚本之家网站内容还不错,欢迎将脚本之家网站推荐给程序员好友。 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
热点阅读
