对于基础功能的支持,在很多项目中都需要用Excel将初始化数据库,其实mysql的工具也是支持用工具的方式导入Excel数据,对于开发人员来说,如果遇到一个后台系统,则通常都需要支持界面操作导入excel数据。
一:前端
通过ajax方式
data: new FormData($("#batchImportProductForm")[0])
二:服务端接受
@RequestMapping(value = "batchImport.do")
@ResponseBody
public Object batchImportCatalogueGroup(HttpServletRequest request, @RequestParam(value = "productImportFile") MultipartFile productImportFile) {
parseRankImportFile(productImportFile)
}
在调用方法解析excel的时候 可以使用泛型的方式 ,抽出工具类,这样可以在其他地方使用,这个地方改造还是有些麻烦,因为对于不同的数据,字段差异很大,提供一个思路吧。
private List<TnCatalogueGroupEntity> parseRankImportFile(InputStream inputStream) {
List<TnCatalogueGroupEntity> productEntityList = new ArrayList<TnCatalogueGroupEntity>();
// 获得Workbook工作薄对象
Workbook workbook;
try {
workbook = new XSSFWorkbook(inputStream);
} catch (Exception e) {
throw new BusinessException("-1", "读取Excel文件失败, 请再试一次", e);
}
Date now = new Date();
// 获得sheet对象
Sheet sheet = workbook.getSheetAt(0);
if (sheet == null) {
throw new BusinessException("-1", "没有找到工作表, 请下载模板编辑后重新导入");
}
for (int rowIndex = 0; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
int lineNumber = rowIndex + 1;
Row row = sheet.getRow(rowIndex);
if (null == row) {
throw new BusinessException("-1", "第" + lineNumber + "行出现错误: 不能为空");
}
if (rowIndex < 1) {
continue;
}
//一级分类名称
String catalogue1Name = PoiUtil.getCellValue(row.getCell(0)).trim();
//一级分类编码
String catalogue1Code = PoiUtil.getCellValue(row.getCell(1)).trim();
if (StringUtils.isEmpty(catalogue1Name)) {
// 一级分类名称 为空, 提示错误
throw new BusinessException("-1", "第" + lineNumber + "行出现错误:一级分类名称不能为空");
}
TnCatalogueGroupEntity entity = new TnCatalogueGroupEntity();
entity.setCatalogue1Name(catalogue1Name);
entity.setCatalogue1Code(catalogue1Code);
entity.setCatalogue2Name(catalogue2Name);
entity.setCatalogue2Code(catalogue2Code);
entity.setLevel4GroupCode(level4GroupCode);
entity.setLevel4GroupName(level4GroupName);
entity.setCreateTime(now);
entity.setUpdateTime(now);
productEntityList.add(entity);
}
return productEntityList;
}
XSSFWorkbook
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.8</version> </dependency>