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