poi读取word

来源:互联网 发布:淘宝上怎么好评改差评 编辑:程序博客网 时间:2024/06/05 07:31
有一个新的需求读取world文件将数据导入数据库中
核心思路:
    通过poi 使用流通过循环遍历表格中的数据,在通过数组得到对应的数据转换为对象,存储到数据库中

package poi_test;import org.apache.poi.hwpf.HWPFDocument;import org.apache.poi.hwpf.usermodel.*;import org.apache.poi.poifs.filesystem.POIFSFileSystem;import java.io.FileInputStream;import java.io.IOException;public class ReadWord {    public void getWordTable(String filePath) throws IOException{        FileInputStream fileInputStream = null;        POIFSFileSystem poifsFileSystem = null;        HWPFDocument hwpfDocument = null;        try{            fileInputStream=new FileInputStream(filePath);//读取文档            poifsFileSystem=new POIFSFileSystem(fileInputStream);//创建poi流对象            hwpfDocument=new HWPFDocument(poifsFileSystem);            Range range=hwpfDocument.getRange();//得到文档的读取范围            TableIterator tableIterator=new TableIterator(range);            while(tableIterator.hasNext()){                Table table=(Table)tableIterator.next();                for(int i=0;i<table.numRows();i++){                    TableRow tableRow=table.getRow(i);                    for(int j=0;j<tableRow.numCells();j++){                        TableCell tableCell=tableRow.getCell(j);//取得单元格                        //取得单元格内容                        for(int k=0;k<tableCell.numParagraphs();k++){                            Paragraph paragraph=tableCell.getParagraph(k);                            String content=paragraph.text();                            System.out.println(content);                            System.out.println("----------");                        }                    }                }            }        }catch (Exception e){            System.out.println(e.getMessage());        }finally {            hwpfDocument.close();            poifsFileSystem.close();            fileInputStream.close();        }    }}
<!--Apache POI [1]  是用Java编写的免费开源的跨平台的 Java API  Apache POI提供APIJava程式对Microsoft Office格式档案读和写的功能--><dependency>  <groupId>org.apache.poi</groupId>  <artifactId>poi</artifactId>  <version>3.17</version></dependency><dependency>  <groupId>org.apache.poi</groupId>  <artifactId>poi-scratchpad</artifactId>  <version>3.17</version></dependency>
原创粉丝点击