目录
1、使用Apache POI框架读取Excel文件
Java读取Excel文件,并过滤空行,且读取多个工作表
package com.boredou.boredou.test;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class ReadExcel {
public static void main(String[] args) {
try {
// 创建输入流
String filePath = "C:\\Users\\Administrator\\Desktop\\1.xlsx";
int suffix = filePath.lastIndexOf(".");
//获取文件后缀名
String substring = filePath.substring(suffix + 1);
if (!"xlsx".equals(substring) && !"xls".equals(substring)) {
System.out.printf("不是excel文件");
}
//xlsx
FileInputStream fis = new FileInputStream(filePath);
// 创建工作簿对象
Workbook workbook = null;
if ("xlsx".equals(substring) ) {//xlsx
workbook = WorkbookFactory.create(fis);
}else {//xls
workbook = new XSSFWorkbook(fis);
}
// 获取第一个工作表
Sheet sheet = workbook.getSheetAt(0);
// 获取行数和列数
int rowCount = sheet.getLastRowNum() + 1;
int columnCount = sheet.getRow(0).getLastCellNum();
// 循环遍历每一行
for (int i = 0; i < rowCount; i++) {
Row row = sheet.getRow(i);
// 判断是否为空行
boolean isRowEmpty = true;
for (int j = 0; j < columnCount; j++) {
//在调用row.getCell(j)方法之前,可以先检查当前行是否为空或是否为null。
if (row != null && row.getRowNum() >= 0) {
Cell cell = row.getCell(j);
if (cell != null && cell.getCellType() != CellType.BLANK) {
isRowEmpty = false;
break;
}
}
}
if (isRowEmpty) {
continue;
}
// 遍历每一列
for (int j = 0; j < columnCount; j++) {
Cell cell = row.getCell(