POI读写word2007文档方法代码



POI读写word2007文档方法代码

1.到Apace官网下载poi-bin-3.10-beta1-20130628.tar.gz的架包

代码如下

import org.apache.poi.xwpf.usermodel.*;

public static void rw07word(String fileName,String path){

try {
FileInputStream in = new FileInputStream(new File(fileName));
//WordExtractor ex = new WordExtractor(in);

//OPCPackage opcPackage = POIXMLDocument.openPackage(“d:/aa.docx”);
XWPFDocument xwpf = new XWPFDocument(in);//得到word文档的信息
List<XWPFRun> listRun;
List<XWPFParagraph> listParagraphs = xwpf.getParagraphs();//得到段落信息
System.out.println(listParagraphs.get(0).getRuns().get(0).getText(0));
listParagraphs.get(0).getRuns().get(0).setText(“标题”,0);//修改段落信息
Iterator<XWPFTable> it = xwpf.getTablesIterator();//得到word中的表格
while(it.hasNext()){
XWPFTable table = it.next();
List<XWPFTableRow> rows=table.getRows();
XWPFTableRow row = rows.get(1);
List<XWPFTableCell> cells = row.getTableCells();
XWPFTableCell cell = cells.get(2);
cell.removeParagraph(0);
cell.setText(“修改后的文字”);//根据行列来设置单元格的信息
List<XWPFParagraph> pars = cell.getParagraphs();
for (XWPFParagraph par:pars){
List<XWPFRun> runs = par.getRuns();
for (XWPFRun run:runs){
run.removeBreak();
}
}
}
FileOutputStream fos = new FileOutputStream( path+”/”+fileName);
xwpf.write(fos);
fos.flush();
fos.close();
System.out.println(fileName+”success”);
}catch(Exception e){
e.printStackTrace();
}
}