1:通过fileUrl文件路径上传
String filePath = map.get(“fileUrl”).toString();
if (StringUtils.isBlank(filePath)) {
throw new TRetailBizException(“上传文件地址不能为空”);
}
File file = new File(filePath);
if (!file.exists()) {
//创建临时目录
file.mkdir();
}
HSSFWorkbook workbook = new HSSFWorkbook(FileUtils.openInputStream(file));
//读取默认第一个工作表sheet
HSSFSheet sheet = workbook.getSheetAt(BusinessConstant.ZERO);
if (sheet.getLastRowNum() == BusinessConstant.ZERO) {
throw new TRetailBizException(“导入的excel有误,请重新导入”);
}
// 遍历每行数据
for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
Row row = sheet.getRow(rowNum);
row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
String code = row.getCell(0).getStringCellValue() == null ? “” : row.getCell(0).getStringCellValue();
String type = row.getCell(1).getStringCellValue() == null ? “” : row.getCell(1).getStringCellValue();
if (StringUtils.isBlank(code) || StringUtils.isBlank(type)) {
continue;
}
codes.add(code);
types.add(Integer.parseInt(type));
}
2:MultipartFile上传excel
Workbook wb = null;
if (!file.isEmpty()) {
String originalFileName = file.getOriginalFilename();
String fileType = originalFileName.substring(originalFileName.lastIndexOf("."));
InputStream inputStream = file.getInputStream();
if (".xls".equals(fileType)) {
wb = new HSSFWorkbook(inputStream);
} else if (".xlsx".equals(fileType)) {
wb = new XSSFWorkbook(inputStream);
}
if (null == wb) {
throw new TRetailBizException(“导入的excel有误,请重试”);
}
Sheet sheet = wb.getSheetAt(BusinessConstant.ZERO);
if (sheet.getLastRowNum() == BusinessConstant.ZERO) {
throw new TRetailBizException(“导入的excel有误,请重新导入”);
}
// 遍历每行数据
for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
Row row = sheet.getRow(rowNum);
row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
//第一列
String code = row.getCell(0).getStringCellValue() == null ? “” : row.getCell(0).getStringCellValue();
//第二列
String type = row.getCell(1).getStringCellValue() == null ? “” : row.getCell(1).getStringCellValue();
if (StringUtils.isBlank(code) || StringUtils.isBlank(type)) {
continue;
}
codes.add(code);
types.add(Integer.parseInt(type));
}