具体就是把Excel中的内容设值到model中。在列表中展示。字段要对应。
不是上传文件。不是上传文件。不是上传文件。
//QuoteProductController.java
/**导入报价产品
*/
@RequestMapping(value="/importData.do")
@ResponseBody
public String importData(SolutionProductImportModel model ,HttpServletRequest request ,HttpServletResponse response) throws Exception{
String filename = model.getFile().getOriginalFileName();//model中file类型为 MultipartFile,要导入的文件。
String fileType = filename.substring(model.getFile().getOriginalFilename().lastIndexOf(".")); //就是截取 [ .+后面的]
try{
if(".xls".equals(fileType)){
//导入前,删除当前报价下的所有产品信息
importMapper.delete(model.getQuoteId());
//导入--读取excel内容到model中
List<String> errorList = new LinkedList<String>();//用来装自定义的错误信息?
List<SolutionProductImportModel> list = readExcel(model.getFile().getInputStream(), model.getQuoteId(), errorList);
if(errorList.isEmpty()){ //读取excel信息到model的过程中没有错误发生。说明导入成功
if(list.size() > 0){
importMapper.importDatas(list);
return StringUtils.resultSuccessToJson("导入成功!");
}
errorList.add("无可导入的数据"); //说明没数据
}
return StringUtils.resultFailToJson(errorList); //读取excel信息到model的过程中有错误发生,导入失败。
}else{ //说明文件格式不是”.xls“
return StringUtils.resultFailToJson("您上传的文件格式有误,请上传xls格式的文件!");
}
}catch(Exception e){
return StringUtils.resultFailToJson(e);
}
//读取Excel内容到model中
public static List<SolutionProductImportModel> readExcel(InputStream is ,String quoteId,list<String> errorList)throws Exception{
//创建一个excelList 用来存储读取的内容
List<SolutionProductImportModel> excelList = new LinkedList<>();
//获取Excel文件对象
Workbook wb = Workbook.getWorkbook(is);
try{
//获取文件的指定工作表 默认的第一个
Sheet sheet = wb.getSheet(0);
Cell cell1 = ExcelUtils.getCellByValue(sheet,"物料号");
Cell cell2 = ExcelUtils.getCellByValue(sheet,"数量");
Cell cell3 = ExcelUtils.getCellByValue(sheet,"意向单价");
Cell cell4 = ExcelUtils.getCellByValue(sheet,"质保期");
if(cell1 == null || cell2 == null || cell3 == null || cell4 == null ){
errorList.add("模板格式不正确"); //如果获取的第一张表的对应的格子是空的,就说明模板有问题。
return excelList;
}
int row_i = cell1.getRow() +1;
/*************循环开始**********/
for(int i = row_i ; ; i++){ //没有结束条件语句
StringBuffer error = new StringBuffer();
Cell val1 = sheet.getCell( cell1.