第一步:引入相关依赖

<dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.2</version>
</dependency>

第二步:工具类

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;public class ImportExcel
{/** 总行数 */private int totalRows = 0;/** 总列数 */private int totalCells = 0;/** 错误信息 */private String errorInfo;public int getTotalRows(){return totalRows;}public void setTotalRows(int totalRows){this.totalRows = totalRows;}public int getTotalCells(){return totalCells;}public void setTotalCells(int totalCells){this.totalCells = totalCells;}public String getErrorInfo(){return errorInfo;}public void setErrorInfo(String errorInfo){this.errorInfo = errorInfo;}/** 构造方法 */public ImportExcel(){}/**** @描述:是否是2003的excel,返回true是2003** @参数:@param filePath 文件完整路径** @参数:@return** @返回值:boolean*/public static boolean isExcel2003(String filePath){return filePath.matches("^.+\\.(?i)(xls)$");}/**** @描述:是否是2007的excel,返回true是2007** @参数:@param filePath 文件完整路径** @参数:@return** @返回值:boolean*/public static boolean isExcel2007(String filePath){return filePath.matches("^.+\\.(?i)(xlsx)$");}public static boolean isCSV(String filePath){return filePath.matches("^.+\\.(?i)(csv)$");}public static boolean isTxt(String filePath){return filePath.matches("^.+\\.(?i)(txt)$");}/**** @描述:验证excel文件** @参数:@param filePath 文件完整路径** @参数:@return** @返回值:boolean*/public boolean validateExcel(String filePath){/** 检查文件名是否为空或者是否是Excel格式的文件 */if (filePath == null || !(ImportExcel.isExcel2003(filePath) || ImportExcel.isExcel2007(filePath) )){errorInfo = "文件名不是excel格式";return false;}return true;}public List read(String filePath, Class cla, Integer sheetNo,Integer startRow){try{if( startRow == null){startRow = 1;}List<Object> listObjects = new ArrayList<Object>();List<List<String>> list = read(filePath,sheetNo, startRow);Constructor[] constructors = cla.getDeclaredConstructors();Constructor<?> constructor = null;for (Constructor<?> item : constructors){if (item.getParameterTypes().length == 1)//获取一个参数的构造方法{constructor = item;}}if (list != null){for (int i = 0; i < list.size(); i++){Object p = cla.newInstance();List<String> cellList = list.get(i);p = constructor.newInstance(cellList);listObjects.add(p);}}return listObjects;}catch (InstantiationException e){e.printStackTrace();errorInfo = "解析excel数据出现错误";return null;}catch (IllegalArgumentException e){e.printStackTrace();errorInfo = "解析excel数据出现错误";return null;}catch (IllegalAccessException e){e.printStackTrace();errorInfo = "解析excel数据出现错误";return null;}catch (InvocationTargetException e){e.printStackTrace();errorInfo = "excel文件模版错误";return null;}catch (SecurityException e){e.printStackTrace();errorInfo = "解析excel数据出现错误";return null;}}/**** @描述:根据文件名读取excel文件** @参数:@param filePath 文件完整路径** @参数:@return** @返回值:List*/public List<List<String>> read(String filePath, Integer sheetNo,Integer startRow){List<List<String>> dataLst = new ArrayList<List<String>>();InputStream is = null;try{/** 验证文件是否合法 */if (!validateExcel(filePath)){System.out.println(errorInfo);return null;}/** 判断文件的类型,是2003还是2007 */boolean isExcel2003 = true;if (ImportExcel.isExcel2007(filePath)){isExcel2003 = false;}/** 调用本类提供的根据流读取的方法 */File file = new File(filePath);is = new FileInputStream(file);dataLst = read(is, isExcel2003, sheetNo, startRow);is.close();}catch (Exception ex){ex.printStackTrace();}finally{if (is != null){try{is.close();}catch (IOException e){is = null;e.printStackTrace();}}}/** 返回最后读取的结果 */return dataLst;}/**** @描述:根据流读取Excel文件** @参数:@param inputStream** @参数:@param isExcel2003** @参数:@return** @返回值:List*/public List<List<String>> read(InputStream inputStream, boolean isExcel2003, Integer sheetNo,Integer startRow){List<List<String>> dataLst = null;try{/** 根据版本选择创建Workbook的方式 */Workbook wb = null;if (isExcel2003){wb = new HSSFWorkbook(inputStream);}else{wb = new XSSFWorkbook(inputStream);}dataLst = read(wb, sheetNo, startRow);}catch (IOException e){e.printStackTrace();}return dataLst;}/**** @描述:读取数据** @参数:@param Workbook** @参数:@param sheetNo** @参数:@return** @返回值:List<List<String>>*/private List<List<String>> read(Workbook wb, Integer sheetNo,Integer startRow){List<List<String>> dataLst = new ArrayList<List<String>>();/** 得到第一个shell */Sheet sheet = null;if(sheetNo == null){sheet = wb.getSheetAt(0);}else{sheet = wb.getSheetAt(sheetNo.intValue());}/** 得到Excel的行数 */this.totalRows = sheet.getPhysicalNumberOfRows();/** 得到Excel的列数 */if (this.totalRows >= 1 && sheet.getRow(startRow) != null){this.totalCells = sheet.getRow(startRow).getPhysicalNumberOfCells();}/** 循环Excel的行 */for (int r = startRow; r < this.totalRows; r++){Row row = sheet.getRow(r);if (row == null){continue;}List<String> rowLst = new ArrayList<String>();/** 循环Excel的列 */for (int c = 0; c < this.getTotalCells(); c++){Cell cell = row.getCell(c);String cellValue = "";if (null != cell){// 以下是判断数据的类型switch (cell.getCellType()){case NUMERIC: // 数字cellValue = String.valueOf(cell.getNumericCellValue());break;case STRING: // 字符串cellValue = cell.getStringCellValue();break;case BOOLEAN: // BooleancellValue = cell.getBooleanCellValue() + "";break;case FORMULA: // 公式cellValue = cell.getCellFormula() + "";break;case BLANK: // 空值cellValue = "";break;case ERROR: // 故障cellValue = "非法字符";break;default:cellValue = "未知类型";break;}}rowLst.add(cellValue);}/** 保存第r行的第c列 */dataLst.add(rowLst);}return dataLst;}}

第三步:运行

/**** @描述:main测试方法** @参数:@param args** @参数:@throws Exception** @返回值:void*/
public static void main(String[] args) throws Exception{ImportExcel poi = new ImportExcel();List<List<String>> list = poi.read("/Users/zhuangjy/Desktop/test.xlsx",1,0);if (list != null) {for (int i = 0; i < list.size(); i++) {System.out.print("第" + (i) + "行");List<String> cellList = list.get(i);for (int j = 0; j < cellList.size(); j++) {System.out.print("    " + cellList.get(j));}System.out.println();}}}

效果截图

Java解析excel表格相关推荐

  1. Java解析excel表格中的图片的方式

    我们要用java解析首先得在项目中引入解析excel的相关包,我们这里使用的是apache的poi-3.12.jar来做开发. 首先获取excel文件,获取文件的方式这里就不细说了,获取到文件后,将文 ...

  2. 使用java解析excel表格(包含表头判断)

    1.FileUtils后面接的路径是src下的文件,FileUtils的jar包没有测试过,有待验证: 2.解析表格使用jar包是org.apache.poi的jar包: 3.判断某一行是否是表头下面 ...

  3. POI解析Excel表格

    Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能. 这里实现poi解析Excel表格的例子,导入Exc ...

  4. java访问excel表格_Java读取excel表格(示例代码)

    Java读取excel表格 一般都是用poi技术去读取excel表格的,但是这个技术又是什么呢 什么是Apache POI? Apache POI是一种流行的API,它允许程序员使用Java程序创建, ...

  5. java读写excel表格数据

    java读写excel表格数据 java读写excel表格数据 excel类 package excel;import java.io.File; import jxl.Cell; import jx ...

  6. java解析excel存入map,java解析excel数据,将excel数据转换为实体类,存入数据库

    前一段时间写了一个功能,从数据库中抽取出来的字段,写入到excel文件里:java使用poi把从数据库中取出的数据写入excel 最近实现了一个相反的功能,前台传一个excel文件,在后台解析该exc ...

  7. java解析Excel文件的方法

    java解析Excel文件的方法 介绍 1.1 pom依赖 1.2 将数据流转化为可解析的Workbook类型文件 1.3 解析 1.4 Controller层接收前端传递的Excel文件(前端使用E ...

  8. Java 解析Excel(xls、xlsx两种格式)

    Java 解析Excel(xls.xlsx两种格式) 一.环境 JDK 1.8 二.JAR 1.commons-collections4-4.1.jar 2.poi-3.9-20121203.jar ...

  9. java 浏览器 excel导出excel_使用Java导出Excel表格并由浏览器直接下载——基于POI框架...

    非异步方法 /** * 使用Java导出Excel表格并由浏览器直接下载--基于POI框架 * * @param response * @return * @throws IllegalAccessE ...

最新文章

  1. php5模块怎么下载,centos源码编译php5 mcrypt模块步骤详解
  2. 生成随机字符串的几种常用方式
  3. 【Python】实战多word的内容合并筛选及输出
  4. 步步为营UML建模系列总结
  5. AngularJS学习!
  6. Netweaver和CloudFoundry的log设置
  7. 女垒姑娘最漂亮,青年女足最顽强
  8. AngularJS-demo - 常用命令、内置服务、自定义服务、继承
  9. 诗与远方:无题(二十二)
  10. PowerShell命令测试--whatif参数
  11. 【Oracle 数据迁移】环境oracle 11gR2,exp无法导出空表的表结构【转载】
  12. 玩转直播+短视频 京东打造“史上最简单618”
  13. Spark Standalone架构设计要点分析
  14. Linux基础三(软件安装管理)
  15. 拓端tecdat|R语言主成分分析(PCA)葡萄酒可视化:主成分得分散点图和载荷图
  16. vue实现导出excel,pdf功能
  17. github创建仓库以及上传项目到github
  18. 和NeroBlack合作的流体教学在AboutCG发布
  19. 浅谈工业互联网与产业互联网区别
  20. 重命名多个图片文件,并修改图片后缀名

热门文章

  1. java占位符填充_程序员:深入理解Java虚拟机,对象的内存布局
  2. Python中为啥 ‘abcd‘<‘ad‘ 答案他来啦
  3. Linux网络协议指令:ifconfig/netstat(net-tools)工具 .vs. iproute2
  4. Linux中shell运行方式,linux脚本中父shell与子shell 执行的几种方式
  5. Flink算子(Filter、KeyBy、Reduce和Aggregate)
  6. flask的请求与响应
  7. python之pymysql的使用
  8. jitpack第三方依赖库使用
  9. navicat 结合快捷键
  10. mfc formview中的关闭视图函数_VC|API消息处理(回调函数+分支语句)与MFC中的消息映射函数...