《java用poi实现对word读取和修改操作》由会员分享,可在线阅读,更多相关《java用poi实现对word读取和修改操作(3页珍藏版)》请在金锄头文库上搜索。
1、 java用poi实现对word读取和修改操作新增WordUtil类,将代码拷进去直接运行即可package com.cjhxfund.ats.fm.instr;import java.io.FileOutputStream;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Map.Entry;import java.util.Set;import org.apache.poi.POIXMLDocument;import o
2、rg.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 W
3、ordUtil public static void searchAndReplace(String srcPath, String destPath, Map map) try XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage(srcPath); / 替换段落中的指定文字 Iterator itPara = document.getParagraphsIterator(); while (itPara.hasNext() XWPFParagraph paragraph = (XWPFParagraph) i
4、tPara.next(); /String s = paragraph.getParagraphText(); Set set = map.keySet(); Iterator iterator = set.iterator(); while (iterator.hasNext() String key = iterator.next(); List runs=paragraph.getRuns(); for (XWPFRun run : runs) String text = run.getText(0); if(text != null) /String runText = run.toS
5、tring(); if(text.indexOf(key) != -1) text = text.replace(key, map.get(key); System.out.println(key=+key+runText=+text); run.setText(text,0); / 替换表格中的指定文字 Iterator itTable = document.getTablesIterator(); while (itTable.hasNext() XWPFTable table = (XWPFTable) itTable.next(); int rcount = table.getNumb
6、erOfRows(); for (int i = 0; i rcount; i+) XWPFTableRow row = table.getRow(i); List cells = row.getTableCells(); for (XWPFTableCell cell : cells) for (Entry e : map.entrySet() if (cell.getText().equals(e.getKey() cell.removeParagraph(0); cell.setText(e.getValue(); FileOutputStream outStream = null; o
7、utStream = new FileOutputStream(destPath); document.write(outStream); outStream.close(); catch (Exception e) e.printStackTrace(); public static void main(String args) throws Exception Map map = new HashMap(); map.put(附件, 文件); map.put(结果, 结束); /map.put(金额, 数量); String srcPath = D:10测试java读取【word】文档内容_V1.0.doc; String destPath = D:10out.doc; searchAndReplace(srcPath, destPath, map);