import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
public class ExcelUtils {
private final static Logger logger = LoggerFactory.getLogger(ExcelUtils.class);
private static Workbook read(String filePath) {
if (filePath == null) {
return null;
}
String ext = filePath.substring(filePath.lastIndexOf("."));
try {
FileInputStream inputStream = new FileInputStream(filePath);
return readFromInputStream(inputStream, ext);
} catch (FileNotFoundException e) {
logger.error("FileNotFoundException", e);
}
return null;
}
private static Workbook readFromInputStream(InputStream inputStream, String ext) {
try {
return (!".xls".equals(ext)) ?
(".xlsx".equals(ext) ? new XSSFWorkbook(inputStream) : null) : new HSSFWorkbook(inputStream);
} catch (FileNotFoundException e) {
logger.error("FileNotFoundException", e);
} catch (IOException e) {
logger.error("IOException", e);
}
return null;
}
private static List<List<String>> readExcelContentList(Workbook wb) {
if (wb != null) {
List<List<String>> content = new ArrayList<>();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.getRow(0);
int rowNum = sheet.getLastRowNum();
int colNum = row.getPhysicalNumberOfCells();
for (int ri = 1; ri <= rowNum; ri++) {
row = sheet.getRow(ri);
int ci = 0;
List<String> col = new ArrayList<>();
while (ci < colNum) {
Object obj = getCellFormatValue(row.getCell(ci++));
obj = (obj instanceof Date) ? simpleDateFormat.format((Date) obj) : obj;
col.add((String) obj);
}
long count = col.stream().filter(StringUtils::isNoneBlank).count();
Optional.of(col).filter(x -> count > 0).ifPresent(content::add);
}
return content;
}
return null;
}
private static Object getCellFormatValue(Cell cell) {
Object cellvalue = "";
if (cell != null) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
case Cell.CELL_TYPE_FORMULA:
cellvalue = DateUtil.isCellDateFormatted(cell) ? cell.getDateCellValue() : String.valueOf(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:// 如果当前Cell的Type为STRING
cellvalue = cell.getRichStringCellValue().getString();
break;
default:
break;
}
}
return cellvalue;
}
public static List<List<String>> readExcel(String filePath) {
Workbook wb = read(filePath);
return readExcelContentList(wb);
}
public static List<List<String>> readExcelFromInputStream(InputStream inputStream, String ext) {
Workbook workbook = readFromInputStream(inputStream, ext);
return readExcelContentList(workbook);
}
}