Maven依赖
地址
https://mvnrepository.com/artifact/org.apache.poi/poi
https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml
说明
poi:读取
Excel 2003
及以下版本的文件,也就是后缀为.xls
的文件Workbook workbook = new HSSFWorkbook();
poi-ooxml:读取
Excel 2007
及以上的文件,也就是后缀为.xlsx
的文件Workbook workbook =new XSSFWorkbook();
获取Workbook对象
方式一:通过文件流的方式
public static Workbook getWorkbook(String filePath) {
InputStream inputStream = null;
try {
inputStream = new FileInputStream(filePath);
//获取文件库扩展名,使用依赖库:https://mvnrepository.com/artifact/commons-io/commons-io
String extension = FilenameUtils.getExtension(filePath);
Workbook workbook = null;
if (extension.equals("xls")) {//2003-
workbook = new HSSFWorkbook(inputStream);
} else if (extension.equals("xlsx")) {//2007+
workbook = new XSSFWorkbook(inputStream);
}
return workbook;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
Sheet相关
前提,定义可用的Workbook:Workbook workbook
当前Excel文件Sheet页的个数
int numberOfSheets = workbook.getNumberOfSheets();
通过索引获取Sheet对象
- 索引从0开始
- 参数为无效的索引会发生异常:
Exception in thread "main" java.lang.IllegalArgumentException: Sheet index (4) is out of range (0..2)
Sheet sheet = workbook.getSheetAt(0);
通过Sheet名称获取Sheet对象
- 参数名称不区分大小写
- 输入无效的不存在的名称参数,返回null
Sheet sheet = workbook.getSheet("sheet1");
根据索引直接获取Sheet的名称
- 索引从0开始
- 无效的索引会发生异常:
Exception in thread "main" java.lang.IllegalArgumentException: Sheet index (4) is out of range (0..2)
String sheetName = workbook.getSheetName(1);
获取当前默认激活的Sheet页索引
- 索引从0开始
int activeSheetIndex = workbook.getActiveSheetIndex();
根据Sheet名称,获取Sheet索引
- 索引从0开始
- 名称不区分大小写
int sheet = workbook.getSheetIndex("sheet2");
获取最后一行
- 之前有内容的单元格后被重置为空,在计算时可能被计算为行,所以在实际返回值可能高于预期
int lastRowNum = sheet.getLastRowNum();