POI读取word文件,(支持HSSF和XSSF两种方式)
生活随笔
收集整理的這篇文章主要介紹了
POI读取word文件,(支持HSSF和XSSF两种方式)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
POI讀取word文件,(支持HSSF和XSSF兩種方式)
參考:HSSF,XSSF,SXSSF三種方式
1.引用maven(版本必須一致)
<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.1</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.1</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-scratchpad</artifactId><version>4.1.1</version></dependency>2.讀取word
public class POIUtil {/*** @Description: POI 讀取 word* @create: 2019-07-27 9:48* @update logs*/public static String readWord(String path) throws Exception {// WordExtractor extractor = new WordExtractor(is);String content = null;File file = new File(path);if (file.exists() && file.isFile()) {InputStream is = null;XWPFDocument xwpfDocument = null;POIXMLTextExtractor extractor = null;HWPFDocument hwpfDocument = null;WordExtractor wordExtractor = null;try {is = new FileInputStream(file);xwpfDocument = new XWPFDocument(is);extractor = new XWPFWordExtractor(xwpfDocument);// 文檔文本內容content = extractor.getText(); // // 文檔圖片內容 // List<XWPFPictureData> pictures = docx.getAllPictures(); // for (XWPFPictureData picture : pictures) { // byte[] bytev = picture.getData(); // // 輸出圖片到磁盤 // FileOutputStream out = new FileOutputStream( // "D:\\temp\\temp\\" + UUID.randomUUID() + picture.getFileName()); // out.write(bytev); // out.close(); // }} catch (FileNotFoundException e) {} catch (IOException e) {} catch (OLE2NotOfficeXmlFileException e) {//較低版本的word文件is = new FileInputStream(file);hwpfDocument = new HWPFDocument(is);wordExtractor = new WordExtractor(hwpfDocument);// 文檔文本內容content = wordExtractor.getText();} finally {try {if (extractor != null) {extractor.close();}if (xwpfDocument != null) {xwpfDocument.close();}if (wordExtractor != null) {wordExtractor.close();}if (hwpfDocument != null) {hwpfDocument.close();}if (is != null) {is.close();}} catch (IOException e) {}}}return content;}public static void main(String[] args) {String path = "/Users/jj/Desktop/勝多負少的范德薩.doc"; // String path = "/Users/jj/Desktop/測試1 2.doc"; // String path = "/Users/jj/Desktop/測試1.docx";try {System.out.println(readWord(path));} catch (Exception e) {e.printStackTrace();}}}總結
以上是生活随笔為你收集整理的POI读取word文件,(支持HSSF和XSSF两种方式)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 骁龙660鸿蒙系统,骁龙660双摄测试机
- 下一篇: python函数可以提高运行效率吗_py