JAVA读取Doc、Docx及注意点

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34461514/article/details/78756113

读取doc、docx、xls、xlsx文件所需的包(红框中)

1. 首先,是通用的读取方法:

读取doc

private static String s_of_Doc(File file){
        String str = "";
        try {
            FileInputStream fis = new FileInputStream(file);
            HWPFDocument doc = new HWPFDocument(fis);
            str = doc.getDocumentText();
            doc.close();
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

读取docx

private static String s_of_Docx(File file){
        String str = "";
        try {
            FileInputStream fis = new FileInputStream(file);
            XWPFDocument xdoc = new XWPFDocument(fis);
            XWPFWordExtractor extractor = new XWPFWordExtractor(xdoc);
            str = extractor.getText();
            extractor.close();
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

2. 两种文件中对换行解释的不同:

·doc 中,换行符是字符13(\r,回车)

·docx 中,换行符是字符10(\n,换行)


JAVA Swing中,文本域(如 JTextPane 等)无法识别 字符13 ,需要将 字符13 转换为字符 10


3. 读取到最后可能会有‘本文结束符’ 字符3‘传输结束符’ 字符4,应该对这两种情况加以特殊判断:

if(chars[i]==3||chars[i]==4)
    break;

猜你喜欢

转载自blog.csdn.net/qq_34461514/article/details/78756113