java如何利用poi解析doc和docx中的數據
前言
這個功能是工作中遇到的一個需求,需要把上傳的word中的內容解析出來,其中包含段落字符串解析,和表格中的數據解析出來,需要支持doc和docx格式的數據
Apache POI是Apache軟件基金會的開源項目,POI提供API給Java程序對Microsoft Office格式檔案讀和寫的功能。 .NET的開發人員則可以利用NPOI (POI for .NET) 來存取 Microsoft Office文檔的功能。
方法如下:
1、增加maven中的包
<dependency><groupId>org.apache.poi</groupId><artifactId>poi-scratchpad</artifactId><version>3.17</version></dependency><!--POI包 --><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.17</version></dependency>
2、解析doc中的數據
獲取文件,把MultipartFile對象的數據轉成本地file
File file = new File(FileUtils.getUserDirectoryPath() + '/' + multipartFile.getOriginalFilename());FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file);
String fileName = file.getName().toLowerCase();FileInputStream in = new FileInputStream(file);if (fileName.endsWith('.doc')) { // 處理doc格式 即office2003版本 handlerDoc(in);}if (fileName.endsWith('.docx')) { handlerDocx(in);}
解析doc格式中的段落和第一個表格數據
/** * doc 格式解析 * * @param in * @throws IOException */ private void handlerDoc(FileInputStream in) throws IOException {POIFSFileSystem pfs = new POIFSFileSystem(in);HWPFDocument hwpf = new HWPFDocument(pfs);//得到文檔的讀取范圍Range range = hwpf.getRange();for (int i = 0; i < range.numParagraphs(); i++) { //段落 Paragraph p = range.getParagraph(i); //段落文本 String paragraphText = p.text().replace('r', ''); log.info('paragraphText = {}', paragraphText ); if (paragraphText.contains(VALUE_YLYC)) {analyze = false; }}TableIterator it = new TableIterator(range);// 迭代文檔中的表格// 如果有多個表格只讀取需要的一個 set是設置需要讀取的第幾個表格,total是文件中表格的總數int set = 1, total = 1;int num = set;for (int i = 0; i < set - 1; i++) { it.hasNext(); it.next();}while (it.hasNext()) { Map<String, List<String>> tabelText = DocUtils.getTabelDocText((Table) it.next()); log.info('tabelText = {}', tabelText);}// 過濾多余的表格while (num < total) { it.hasNext(); it.next(); num += 1;} }
3、解析docx中數據
解析docx格式中的段落和第一個表格數據
/** * docx 格式解析 * * @param in * @throws IOException */ private void handlerDocx(FileInputStream in) throws IOException {XWPFDocument xwpf = new XWPFDocument(in);// 獲取word中的所有段落與表格List<IBodyElement> elements = xwpf.getBodyElements();// 解析表格后續不解析for (IBodyElement element : elements) { // 段落 if (element instanceof XWPFParagraph) {String paragraphText = DocUtils.getParagraphText((XWPFParagraph) element);log.info('paragraphText = {}', paragraphText); } else if (element instanceof XWPFTable) {// 表格 Map<String, List<String>> tabelText = DocUtils.getTabelText((XWPFTable) element);log.info('tabelText = {}', tabelText); } else {log.info('其他內容'); }} }
工具類
package com.hundsun.fais.innerreport.utils;import org.apache.poi.hwpf.usermodel.Paragraph;import org.apache.poi.hwpf.usermodel.Table;import org.apache.poi.hwpf.usermodel.TableCell;import org.apache.poi.hwpf.usermodel.TableRow;import org.apache.poi.xwpf.usermodel.*;import java.util.*;/** * @author lvbaolin * @date 2021/4/2 10:39 */public class DocUtils { /** * docx 格式獲取表格內容 * * @param table */ public static Map<String, List<String>> getTabelText(XWPFTable table) {Map<String, List<String>> result = new LinkedHashMap<>();List<XWPFTableRow> rows = table.getRows();for (XWPFTableRow row : rows) { String key = null; List<String> list = new ArrayList<>(16); int i = 0; List<XWPFTableCell> cells = row.getTableCells(); for (XWPFTableCell cell : cells) {// 簡單獲取內容(簡單方式是不能獲取字體對齊方式的)StringBuffer sb = new StringBuffer();// 一個單元格可以理解為一個word文檔,單元格里也可以加段落與表格List<XWPFParagraph> paragraphs = cell.getParagraphs();for (XWPFParagraph paragraph : paragraphs) { sb.append(DocUtils.getParagraphText(paragraph));}if (i == 0) { key = sb.toString();} else { String value = sb.toString(); list.add(value == null || Objects.deepEquals(value, '') ? null : value.replace(',', ''));}i++; } result.put(key, list);}return result; } /** * docx 獲取段落字符串 * 獲取段落內容 * * @param paragraph */ public static String getParagraphText(XWPFParagraph paragraph) {StringBuffer runText = new StringBuffer();// 獲取段落中所有內容List<XWPFRun> runs = paragraph.getRuns();if (runs.size() == 0) { return runText.toString();}for (XWPFRun run : runs) { runText.append(run.text());}return runText.toString(); } /** * doc 格式的字段解析表格 * @param tb * @return */ public static Map<String, List<String>> getTabelDocText(Table tb) {Map<String, List<String>> result = new HashMap<>(16);//迭代行,默認從0開始,可以依據需要設置i的值,改變起始行數,也可設置讀取到那行,只需修改循環的判斷條件即可for (int i = 0; i < tb.numRows(); i++) { List<String> list = new ArrayList<>(16); int x = 0; TableRow tr = tb.getRow(i); String key = null; //迭代列,默認從0開始 for (int j = 0; j < tr.numCells(); j++) {//取得單元格TableCell td = tr.getCell(j);StringBuffer sb = new StringBuffer();//取得單元格的內容for (int k = 0; k < td.numParagraphs(); k++) { Paragraph paragraph = td.getParagraph(k); String s = paragraph.text(); //去除后面的特殊符號 if (null != s && !''.equals(s)) {s = s.substring(0, s.length() - 1); } sb.append(s);}if (x == 0) { key = sb.toString();} else { String value = sb.toString(); list.add(value == null || Objects.deepEquals(value, '') ? null : value.replace(',', ''));}x++; } result.put(key, list);}return result; }}
總結
到此這篇關于java如何利用poi解析doc和docx中數據的文章就介紹到這了,更多相關java poi解析doc數據內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: