java 读取word

Posted newlangwen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 读取word相关的知识,希望对你有一定的参考价值。

读取word文件

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import org.apache.poi.POIXMLDocument;
import org.apache.poi.POIXMLTextExtractor;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;

public class WordDemo {
    public static void main(String[] args) {
        StringBuffer readWord = readWord("f:/app代码.docx");
        System.out.println(readWord.toString());
        
    }

    public static StringBuffer readWord(String path) {
        String s = "";
        try {
            if (path.endsWith(".doc")) {
                InputStream is = new FileInputStream(new File(path));
                WordExtractor ex = new WordExtractor(is);
                s = ex.getText();
            } else if (path.endsWith("docx")) {
                OPCPackage opcPackage = POIXMLDocument.openPackage(path);
                POIXMLTextExtractor extractor = new XWPFWordExtractor(opcPackage);
                s = extractor.getText();
            } else {
                System.out.println("传入的word文件不正确:" + path);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        StringBuffer bf = new StringBuffer(s);
        return bf;
    }
}

需要jar包

		<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>3.17</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>3.17</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad -->
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-scratchpad</artifactId>
			<version>3.17</version>
		</dependency>

  

以上是关于java 读取word的主要内容,如果未能解决你的问题,请参考以下文章

《《《java代码读取word文档》》》

Java读取word文件,字体,颜色

怎样在word中高亮显示java代码

JAVA有啥好的方法可以将word里的文本读取出来

Word 文档的优秀代码片段工具或插件?

怎么用Java读取word文档里的内容格式信息,比如标题字体,颜色和段间距啥的?