轉載地址https://www.cnblogs.com/GoForMyDream/p/8559072.html
親測可用
添加依賴
<!-- 導入word需要的 需要導入的依賴 --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.0</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-scratchpad</artifactId> <version>4.1.0</version> </dependency>
因為要新建一個站,公司要把word表格的部分行列存到數據庫中。之前用java操作過excel,本來打算用java從word表格中讀取數據,再存到數據庫中,結果因為權限不夠,無法訪問公司要寫的那個數據庫,跪了跪了。
但還是把java讀取word中表格的方法寫一下,先上代碼。
public static void testWord(String filePath){ try{ FileInputStream in = new FileInputStream(filePath);//載入文檔 //如果是office2007 docx格式 if(filePath.toLowerCase().endsWith("docx")){ //word 2007 圖片不會被讀取, 表格中的數據會被放在字符串的最后 XWPFDocument xwpf = new XWPFDocument(in);//得到word文檔的信息 // List<XWPFParagraph> listParagraphs = xwpf.getParagraphs();//得到段落信息 Iterator<XWPFTable> it = xwpf.getTablesIterator();//得到word中的表格 while(it.hasNext()){ XWPFTable table = it.next(); List<XWPFTableRow> rows=table.getRows(); //讀取每一行數據 for (int i = 1; i < rows.size(); i++) { XWPFTableRow row = rows.get(i); //讀取每一列數據 List<XWPFTableCell> cells = row.getTableCells(); for (int j = 0; j < cells.size(); j++) { XWPFTableCell cell=cells.get(j); //輸出當前的單元格的數據 System.out.println(cell.getText()); } } } } }catch(Exception e) { e.printStackTrace(); } }
首先肯定是io讀取文檔,利用傳進來的地址,接着有一個if判斷語句,這個語句主要是為了判斷word的版本的。因為目前word有doc和docx兩種格式,這兩種處理的方式不太一樣。我這里用的是docx格式,判斷完成后,用XWPFDocument來接收word文檔信息,再用迭代器來便利word中的表格,表格肯定是有行有列,兩個for循環,輸出整個行列。
運行結果