引入依赖
<!-- 引入poi,解析workbook视图 使用 Excel和Word ppt 导入导出所需要-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
创建类 如下(如果您的项目 没有 Slf4j 可 注释掉 相对应的包 注解 以及log日志打印) :
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
@Slf4j
public class ReadExcel {
private static final String EXCEL_XLS = ".xls"; //Excel 2003
private static final String EXCEL_XLSX = ".xlsx";//Excel 2007
private final static String DATE_FORMAT = "yyyy/MM/dd";
/**
* @param file 上传的Excel文件
* @param rowsize 从第几行读取数据
* @param sheetsize 从第几页读取数据
* @return 返回 读取得到的数据
* @throws IOException 如果不是 .xls 和 .xlsx 抛出异常
*/
public static List<String[]> read(MultipartFile file, int rowsize, int sheetsize) throws IOException {
//File fileExcelUrl = new File(url);
//检查文件
checkFile(file);
Workbook excelSuffix = null;
List<String[]> list = null;
try {
//获取 Excel工作簿
excelSuffix = getExcelSuffix(file);
//创建返回对象,把每行中的值作为一个数组,所有行作为一个集合返回
list = new ArrayList<String[]>();
// 获取工作簿下放的 sheet 对应一个工作页
Sheet sheet = excelSuffix.getSheetAt(sheetsize);
// 获得当前sheet的开始行 第一行从0开始算
int firstRowNum = sheet.getFirstRowNum();
//获得当前sheet的结束行
int lastRowNum = sheet.getLastRowNum();
for (int rowNum = firstRowNum + rowsize; rowNum <= lastRowNum; rowNum++) {
//获得当前行
Row row = sheet.getRow(rowNum);
if (row == null) continue;//有可能当前行为空行
//获得当前行的开始列
int firstCellNum = row.getFirstCellNum();
//获得当前行的列数
int lastCellNum = row.getPhysicalNumberOfCells();
String[] cells = new String[row.getPhysicalNumberOfCells()];
//循环当前行
for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {
Cell cell = row.getCell(cellNum);
cells[cellNum] = getCellValue(cell);
}
//添加到集合
list.add(cells);
}
} catch (IOException e) {
log.info("IOException===>{}",e);
} finally {
try {
//关闭
if (excelSuffix != null) excelSuffix.close();
} catch (IOException e) {
log.info("关闭===>{}",e);
}
}
return list;
}
/**
* @param fileExcelUrl 获取文件查看是否合法
* @throws IOException 不合法 抛出异常
*/
private static void checkFile(MultipartFile fileExcelUrl) throws IOException {
//获得文件名
String excelSuffix = fileExcelUrl.getOriginalFilename().substring(fileExcelUrl.getOriginalFilename().lastIndexOf("."));
log.info("文件后缀名===========>{}", excelSuffix);
//判断文件是否存在
if (null == fileExcelUrl) throw new FileNotFoundException("文件不存在!");
if (!EXCEL_XLS.endsWith(excelSuffix) && !EXCEL_XLSX.endsWith(excelSuffix))
throw new IOException(excelSuffix + "不是excel文件,请传入.xls或.xlsx文件!");
}
/**
* @param fileExcelUrl 接收文件 查看后缀名是否输入Excel 2003 2007版本
* @return 返回 工作簿对象
* @throws IOException 不是则抛出异常
*/
public static Workbook getExcelSuffix(MultipartFile fileExcelUrl) throws IOException {
//获得文件名
String excelSuffix = fileExcelUrl.getOriginalFilename().substring(fileExcelUrl.getOriginalFilename().lastIndexOf("."));
//String excelSuffix = fileExcelUrl.getName().substring(fileExcelUrl.getName().lastIndexOf("."));
Workbook workbook = null;
try {
//获取excel文件的io流
InputStream fis = fileExcelUrl.getInputStream();
//根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象
//Excel 2003
if (EXCEL_XLS.endsWith(excelSuffix)) workbook = new HSSFWorkbook(fis);
//Excel 2007
//if (EXCEL_XLSX.endsWith(excelSuffix)) workbook = new SXSSFWorkbook(new XSSFWorkbook(fis));
if (EXCEL_XLSX.endsWith(excelSuffix)) workbook = new XSSFWorkbook(fis);
} catch (IOException e) {
log.info("InputStream ===>{}",e);
}
return workbook;
}
/**
* @param cell 获取当前行的每列的数据
* @return 返回数据
*/
public static String getCellValue(Cell cell) {
String cellValue = "";
if (cell == null) {
return cellValue;
}
//如果当前单元格内容为日期类型,需要特殊处理
String dataFormatString = cell.getCellStyle().getDataFormatString();
if (dataFormatString.equals("yyyy-MM-dd")) {
cellValue = new SimpleDateFormat("yyyy-MM-dd").format(cell.getDateCellValue());
return cellValue;//"2021-04-16"
}
if (dataFormatString.equals("m/d/yy")) {
cellValue = new SimpleDateFormat(DATE_FORMAT).format(cell.getDateCellValue());
return cellValue;//"2021/04/16"
}
//把数字当成String来读,避免出现1读成1.0的情况
if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) cell.setCellType(Cell.CELL_TYPE_STRING);
//判断数据的类型
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC: //数字
cellValue = String.valueOf(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING: //字符串
cellValue = String.valueOf(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN: //Boolean
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA: //公式
cellValue = String.valueOf(cell.getCellFormula());
break;
case Cell.CELL_TYPE_BLANK: //空值
cellValue = "";
break;
case Cell.CELL_TYPE_ERROR: //故障
cellValue = "非法字符";
break;
default:
cellValue = "未知类型";
break;
}
return cellValue;
}
}
使用方法如下: