poi 读取word文档


1.导入jar包

官网下载地址:

https://www.apache.org/dyn/closer.lua/poi/release/bin/poi-bin-3.17-20170915.zip

最开始的时候没有导入xmlbeans包,运行的时候报了个异常,然后学乖了

2.对象的说明

2.1关于word有两个对象;XWPFDocument和HWPFDocument分别对应word2007以上和word2003具体的说明见下面这段话:

来自某位大牛的博客,链接找不到了

2.2

3.读取

 3.1 XWPFDocument读取word,并将其中的图片保存

里面的CTP似乎是封装了文档的属性,但查了很多资料讲的也都很模糊,希望有高手看到可以不吝赐教

 1 @Test  2     public void test1() throws IOException {  3         InputStream is = new FileInputStream(new File("e:/test.docx"));  4         XWPFDocument doc = new XWPFDocument(is);  5         
 6         List<XWPFParagraph> paragraphs = doc.getParagraphs();  7         for(XWPFParagraph paragraph:paragraphs) {  8         // print(paragraph.getText());  9         
10             //获取段落属性
11             /*CTPPr pPr = paragraph.getCTP().getPPr(); 12  print(pPr);*/
13             
14  } 15         
16         //获取表格 表格--->行--->单元格
17         /*List<XWPFTable> tables = doc.getTables(); 18  for(XWPFTable table: tables) { 19  //表格属性 20  print(table.getCTTbl()); 21  List<XWPFTableRow> rows = table.getRows(); 22  for(XWPFTableRow row:rows) { 23  List<XWPFTableCell> tableCells = row.getTableCells(); 24  for(XWPFTableCell cell:tableCells) { 25  print(cell.getText()); 26                     
27  //单元格属性 28  print(cell.getCTTc()); 29                 
30  } 31  } 32  }*/
33         String dirPath = "e:/picture_test_docx/"; 34         File dir = new File(dirPath); 35         if(!dir.exists()) { 36  dir.getParentFile().mkdirs(); 37  } 38         BufferedOutputStream bos =null; 39         //获取图片
40         List<XWPFPictureData> pictures = doc.getAllPictures(); 41         for(XWPFPictureData picture:pictures) { 42             byte[] data = picture.getData(); 43             String picName = picture.getFileName(); 44             print("-------"+picture.getPackagePart());; 45             UUID uuid = UUID.randomUUID(); 46             File file = new File(dirPath+uuid + picName); 47             if(!file.exists()) { 48  file.getParentFile().mkdirs(); 49  file.createNewFile(); 50             }else { 51  file.delete(); 52  } 53             bos =  new BufferedOutputStream(new FileOutputStream(file)); 54  bos.write(data); 55  bos.flush(); 56  }
       bos.close();
57 doc.close(); 58 is.close(); 59 }

 注意看这图,标注的地方,输出的东西,你可能会很奇怪word文档怎么会有包的结构?把word文件改成zip或者rar打开后你就可以发现word的包结构

3.2 XWPFWordExtractor读取

 

ps:用poi用word中插入图片时有个无法显示的bug,网上有一些解决方案,但试了几个都没法用,希望将来有这种需求的时候bug已修复

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM