1.前台传文件
2.后台接收文件并转为实体List
@RequestMapping(value = "/to_impt", method = RequestMethod.POST)
public WebResponseContext toImpt(HttpServletRequest request
, @RequestParam("file") MultipartFile multipartFile
, @RequestParam(value = "handbookNo", required = true) String handbookNo
) {
List<HandbookExportExg> list = FileUtils.importExcel(multipartFile, 0, 1, HandbookExportExg.class);
//把File文件转为List
public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
if (file == null) {
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
List<T> list = null;
try {
list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
} catch (NoSuchElementException e) {
// throw new NormalException("excel文件不能为空");
e.printStackTrace();
} catch (Exception e) {
//throw new NormalException(e.getMessage());
e.printStackTrace();
}
return list;
}
3.进行相关效验后,批量保存到数据库
public void bacthUpdateExg(List<HandbookExgInput> exgInputList, String handbookNo) {
if (exgInputList == null || exgInputList.size() == 0) {
return;
}
//3是测试数据,后续改成50
if (exgInputList.size() <= BATCH_PERSIZE) {
exgInputRepository.batchUpdateExgInput(exgInputList, handbookNo);
return;
}
//对于数量超过N条的分批执行
int exgInputSize = exgInputList.size();
int times = exgInputSize % BATCH_PERSIZE == 0 ? exgInputSize / BATCH_PERSIZE : exgInputSize / BATCH_PERSIZE + 1;
for (int i = 0; i < times; i++) {
int beginIndex = i * BATCH_PERSIZE;
int endIndex = (i + 1) * BATCH_PERSIZE > exgInputSize ? exgInputSize : (i + 1) * BATCH_PERSIZE;
logger.info("批量保存--成品---数据,beginIndex:" + beginIndex + ",endIndex:" + endIndex);
exgInputRepository.batchUpdateExgInput(exgInputList.subList(beginIndex, endIndex), handbookNo);
}
}
本文详细介绍了一个基于Spring MVC的文件上传处理流程,包括前端文件的传输,后端使用MultipartFile接收并转换为实体List,以及如何将这些数据批量保存到数据库的方法。特别关注了数据的批量处理和错误处理策略。
1149

被折叠的 条评论
为什么被折叠?



