1、excel解析任意数据
public class ParseExcelUtil {
private static final Logger logger = LoggerFactory.getLogger(ParseExcelUtil.class);
private static final String OFFICE_EXCEL_XLS = "xls";
private static final String OFFICE_EXCEL_XLSX = "xlsx";
public static List parseFromExcel(MultipartFile file, Integer firstIndex, Integer lastIndex, int[] array, Class aimClass, int sheetNum) {
List result = new ArrayList<>();
//文件格式判断
if (!getSuffix(file)){
return result;
}
Workbook workbook = null;
try {
FileInputStream fis = getFileInputStream(file);
workbook = WorkbookFactory.create(fis);
//对excel文档的第一页,即sheet1进行操作
Sheet sheet = workbook.getSheetAt(sheetNum);
workbook.getActiveSheetIndex();
int lastRaw = lastIndex == null ? sheet.getLastRowNum() : lastIndex;
//自定义从哪行开始读取
for (int i = firstIndex; i <= lastRaw; i++) {
//第i行
Row row = sheet.getRow(i);
//自定义只读取到哪列
T parseObject = aimClass.newInstance();
Field[] fields = aimClass.getDeclaredFields();
for (int j = 0; j < array.length; j++) {
Field field = fields[j];
field.setAccessible(true);
Class> type = field.getType();
//第j列
Cell cell = row.getCell(array[j] - 1);
if (cell == null) {
continue;
}
//日期类型特殊处理,其余类型先统一为字符类型以方便获取再分类判断转换类型赋值
if (type.equals(Date.class)) {
cell.setCellType(CellType.NUMERIC);
Date dateCellValue = cell.getDateCellValue();
field.set(parseObject, dateCellValue);
} else {
cell.setCellType(CellType.STRING);
String cellContent = cell.getStringCellValue();
if (type.equals(String.class)) {
field.set(parseObject, cellContent);
} else if (type.equals(BigDecimal.class)) {
field.set(parseObject, new BigDecimal(cellContent));
}
}
}
result.add(parseObject);
}
fis.close();
workbook.close();
return result;
} catch (Exception e) {
logger.error(e.toString());
} finally {
try {
if (workbook!=null){
workbook.close();
}
} catch (IOException e) {
logger.error(e.toString());
}
}
return result;
}
public static FileInputStream getFileInputStream(String path) throws FileNotFoundException {
FileInputStream fileInputStream = new FileInputStream(path);
return fileInputStream;
}
private static FileInputStream getFileInputStream(MultipartFile file) throws IOException {
return (FileInputStream)file.getInputStream();
}
private static Boolean getSuffix(MultipartFile file) {
if (StringUtils.isBlank(file.getOriginalFilename())) {
return false;
}
int index = file.getOriginalFilename().lastIndexOf(".");
if (index == -1) {
return false;
}
String suffix=file.getOriginalFilename().substring(index + 1, file.getOriginalFilename().length());
if (StringUtils.isBlank(suffix)) {
throw new IllegalArgumentException("文件后缀不能为空");
}
if (!OFFICE_EXCEL_XLS.equals(suffix) && !OFFICE_EXCEL_XLSX.equals(suffix)) {
throw new IllegalArgumentException("该文件非Excel文件");
}
return true;
}
}
2、依赖支持
org.apache.poi
poi
3.17
org.apache.poi
poi-scratchpad
3.17
org.apache.poi
poi-ooxml
3.17
org.apache.poi
poi-ooxml-schemas
3.17
com.google.guava
guava
23.0