文件内容读取工具类,亲测可用

maven依赖:

<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.16</version>
</dependency> <dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.16</version>
</dependency> <dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.16</version>
</dependency> <dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>
<version>2.6.0</version>
</dependency> <dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.1</version>
</dependency>

工具类:

import org.apache.commons.io.FileUtils;
import org.apache.pdfbox.io.RandomAccessBuffer;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.POIXMLTextExtractor;
import org.apache.poi.hslf.extractor.PowerPointExtractor;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xslf.extractor.XSLFPowerPointExtractor;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.xmlbeans.XmlException; import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream; /**
* @author wangshuaijun
* @description
* 读取文件工具类:支持以下文件内容读取
* 1. word(.doc),word(.docx)
* 2. excel(.xls),excel(xlsx)
* 3. pdf
* 4. txt
* 5. ppt(.ppt),pptx(,pptx)
* @date 2019年4月19日10:52:45
*
*/
public class ReadFileUtils { /**
* 根据文件类型返回文件内容
* @param filepath
* @return
* @throws IOException
*/
public static String getContentByPath(String filepath) throws IOException{
String []fileTypeArr=filepath.split( "\\." );
String fileType=fileTypeArr[fileTypeArr.length-1];
if("doc".equals( fileType ) || "docx".equals( fileType )){
return readWord( filepath,fileType );
}else if("xlsx".equals( fileType ) || "xls".equals( fileType )){
return readExcel( fileType,filepath );
}else if("txt".equals( fileType )){
return readTxt(filepath);
}else if("pdf".equals( fileType )){
return readPdf(filepath);
}else if("ppt".equals( fileType ) || "pptx".equals( fileType )){
return readPPT(fileType,filepath);
}else{
System.out.println("不支持的文件类型!");
}
return "";
} /**
* 读取PDF中的内容
* @param filePath
* @return
*/
public static String readPdf(String filePath){
FileInputStream fileInputStream=null;
PDDocument pdDocument=null;
String content="";
try {
//创建输入流对象
fileInputStream = new FileInputStream(filePath);
//创建解析器对象
PDFParser pdfParser = new PDFParser(new RandomAccessBuffer(fileInputStream));
pdfParser.parse();
//pdf文档
pdDocument = pdfParser.getPDDocument();
//pdf文本操作对象,使用该对象可以获取所读取pdf的一些信息
PDFTextStripper pdfTextStripper = new PDFTextStripper();
content = pdfTextStripper.getText(pdDocument);
}catch(IOException e){
e.printStackTrace();
}finally{
try {
//PDDocument对象时使用完后必须要关闭
if(null!=pdDocument){
pdDocument.close();
}
if(null!=fileInputStream){
fileInputStream.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
return content;
} /**
* 读取Excel中的内容
* @param filePath
* @return
* @throws IOException
*/
private static String readTxt(String filePath) throws IOException{
File f = new File(filePath);
return FileUtils.readFileToString( f,"GBK" );
} /**
* 读取Excel中的内容
* @param filePath
* @return
*/
private static String readExcel(String fileType,String filePath){ try {
File excel = new File(filePath);
if (excel.isFile() && excel.exists()) { //判断文件是否存在
Workbook wb;
//根据文件后缀(xls/xlsx)进行判断
if ( "xls".equals(fileType)){
FileInputStream fis = new FileInputStream(excel); //文件流对象
wb = new HSSFWorkbook(fis);
}else if ("xlsx".equals(fileType)){
wb = new XSSFWorkbook(excel);
}else {
System.out.println("文件类型错误!");
return "";
}
//开始解析,获取页签数
StringBuffer sb=new StringBuffer("");
for(int i=0;i<wb.getNumberOfSheets();i++){
Sheet sheet = wb.getSheetAt(i); //读取sheet
sb.append( sheet.getSheetName() +"_");
int firstRowIndex = sheet.getFirstRowNum()+1; //第一行是列名,所以不读
int lastRowIndex = sheet.getLastRowNum();
for(int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) { //遍历行
Row row = sheet.getRow(rIndex);
if (row != null) {
int firstCellIndex = row.getFirstCellNum();
int lastCellIndex = row.getLastCellNum();
for (int cIndex = firstCellIndex; cIndex < lastCellIndex; cIndex++) { //遍历列
Cell cell = row.getCell(cIndex);
if (cell != null) {
sb.append( cell.toString());
}
}
}
}
}
return sb.toString();
} else {
System.out.println("找不到指定的文件");
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
} /**
* 读取word中的内容
* @param path
* @param fileType
* @return
*/
public static String readWord(String path,String fileType) {
String buffer = "";
try {
if ("doc".equals( fileType )) {
InputStream is = new FileInputStream(new File(path));
WordExtractor ex = new WordExtractor(is);
buffer = ex.getText();
ex.close();
} else if ("docx".equals( fileType )) {
OPCPackage opcPackage = POIXMLDocument.openPackage(path);
POIXMLTextExtractor extractor = new XWPFWordExtractor(opcPackage);
buffer = extractor.getText();
extractor.close(); } else {
System.out.println("此文件不是word文件!");
} } catch (Exception e) {
e.printStackTrace();
} return buffer;
} private static String readPPT(String fileType,String filePath) {
try {
if("ppt".equals( fileType )){
PowerPointExtractor extractor=new PowerPointExtractor(new FileInputStream( new File( filePath )));
return extractor.getText();
} else if("pptx".equals( fileType )){
return new XSLFPowerPointExtractor(POIXMLDocument.openPackage(filePath)).getText();
}
}catch (IOException e){
e.fillInStackTrace();
}catch(XmlException e){
e.getMessage();
}catch(OpenXML4JException e){
e.getMessage();
} return "";
}

工具类_JavaPOI_Office文件内容读取的更多相关文章

  1. excel to datatable (c#用NPOI将excel文件内容读取到datatable数据表中)

    将excel文件内容读取到datatable数据表中,支持97-2003和2007两种版本的excel 1.第一种是根据excel文件路径读取excel并返回datatable /// <sum ...

  2. Properties类对于文件的读取和写入

    Properties类表示一个持久的属性集.Properties可保存在流中或从流中加载.Properties对象只能加载以 .Properties 为后缀的文件(文件我创建在src下). 开始时文件 ...

  3. 【转载】ASP.NET工具类:文件夹目录Directory操作工具类

    在ASP.NET开发网站的过程中,有时候会涉及到文件夹相关操作,如判断文件夹目录是否存在.删除文件夹目录.创建文件.删除文件.复制文件夹等等.这一批有关文件目录的操作可以通过Directory类.Fi ...

  4. Java将字符串写入文件与将文件内容读取到字符串

    原文:http://blog.csdn.net/liuweiyuxiang/article/details/69487326 将字符串写入文件 方法一 public void WriteStringT ...

  5. ios本地文件内容读取,.json .plist 文件读写

    ios本地文件内容读取,.json .plist 文件读写 本地文件.json .plist文件是较为常用的存储本地数据的文件,对这些文件的操作也是一种常用的基础. 本文同时提供初始化变量的比较标准的 ...

  6. 文件压缩、解压工具类。文件压缩格式为zip

    package com.JUtils.file; import java.io.BufferedOutputStream; import java.io.File; import java.io.Fi ...

  7. FastDFS 工具类实现文件上传_02

    一.jar 包 jar包下载:https://pan.baidu.com/s/1nwkAHU5 密码:tlv6 或者 下载工程,安装到 maven 本地仓库 工程下载:https://pan.baid ...

  8. ca75a_c++_标准IO库-利用流对象把文件内容读取到向量-操作文件

    /*ca75a_c++_标准IO库习题练习习题8.3,8.4,8.6习题8.9.8.10 ifstream inFile(fileName.c_str());1>d:\users\txwtech ...

  9. robotframework 测试工具添加PDF文件内容匹配插件

    robotframework  这个需要了解的请度娘.本文实现的是一个小功能.大体分为如下几个步骤 1)给定一个pdf文件. 2)读取pdf文件内容,并解析为文本内容. 3)通过给定的内容,比对pdf ...

随机推荐

  1. Vue的学习笔记

    以下文章皆为观看慕课网https://www.imooc.com/learn/796中“河畔一角”老师的讲解做的笔记,仅供参考. 一.Vue特点 Vue是MVVM的框架,也就是模型视图->视图模 ...

  2. vue简单todolist

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  3. JetBrains 系列开发工具 汉化(中文化)教程

    项目地址:(* ̄3 ̄)╭ 操作流程: 拷贝内容 将下载的包改名为resources_cn.jar,拷贝到 $IDEA_HOME$/lib/ 目录下 重启IDEA 打开或者重新启动IDEA

  4. 基于FTP 的本地Yum服务器配置

    服务器端 环境如下 Vmware14CentOS 7.6 192.168.20.81 server 192.168.20.81 client 1.配置yum源 mount /dev/cdrom /me ...

  5. Android笔记(六) Android中的组件

    一个软件可以吸引到用户,除了优秀的功能可以解决用户的问题之外,良好的用户界面也并不可少.一个软件的功能不管多么优秀,但是没有提供友好的界面来让用户操作,将很难吸引到最终用户. Android提供了大量 ...

  6. 关于MySQL中的锁机制详解

    锁概述 MySQL的锁机制,就是数据库为了保证数据的一致性而设计的面对并发场景的一种规则. 最显著的特点是不同的存储引擎支持不同的锁机制,InnoDB支持行锁和表锁,MyISAM支持表锁. 表锁就是把 ...

  7. Windows Server 2016 IIS的安装与配置

    1. 打开服务器管理器,点击[添加角色和功能选项].        2. 进入“添加角色和功能向导”页面,点击下一步. 3. 安装类型选择[基于角色或基于功能的安装],点击下一步. 4. 进入服务器选 ...

  8. mysql 新手入门 官方文档+官方中文文档附地址

    点评: 官方文档地址 官方中文文档地址 sql语句扩展

  9. vue中watch的详细用法(转载)

    在vue中,使用watch来响应数据的变化.watch的用法大致有三种.下面代码是watch的一种简单的用法: <input type="text" v-model=&quo ...

  10. Mac OS终端利器iTerm2(完美替代bash)

    iTerm2 iTerm一个为Mac OS X编写的,功能齐全的终端仿真程序:目标是在为用户提供OS X下最佳的命令行体验,iTerm 2有很多能够提升效率的实用功能.比如说窗口分割.热键窗口.智能搜 ...