一、描述
1.前端
采用的是element组件
<el-upload
class="upload-file"
drag
ref="uploadExcel"
:action="importUrl"
:limit="1"
name="importMatFile"
:auto-upload="false"
accept=".xlsx"
:before-upload="beforeUploadFile"
:on-change="fileChange"
:on-exceed="exceedFile"
:on-success="handleSuccess"
:on-error="handleError"
:file-list="excelFileList"
>
<i class="el-icon-upload"></i>
<div class="el-upload__text">
将文件拖到此处,或<em>点击选择Excel文件</em>
</div>
</el-upload>
2.服务器端
2.1 controller
/**
* 导入数据
* @param file
* @return
* @throws
*/
@RequestMapping(value = "/import", method = RequestMethod.POST)
public R importExcel(@RequestParam("importMatFile") MultipartFile file) throws IOException {
List<ImportMatInfoReqVo> list = ExcelUtils.importExcel(file, ImportMatInfoReqVo.class);
int i = materialService.insertByBatch(list);
if (i != 0) {
return R.ok("导入成功");
} else {
return R.error("导入失败");
}
}
一开始以为是后端没有接收到文件,后来发现是接收到的。问题出在处理文件这个方法上:ExcelUtils.importExcel(file, ImportMatInfoReqVo.class)
这个类用来处理导入的excel数据,将每一行数据转换成一个个bean。
进入这个类,发现其中导入的方法中,有一个参数设置存在问题。params.setNeedSave(true);这个属性是设置要把导入的文件进行保存,默认该参数值是false。我注释掉就可以正常使用了。至于为什么不行,可能是保存路径错误,具体的我暂时没有尝试。
/**
* excel 导入
*
* @param inputStream 文件输入流
* @param titleRows 表格内数据标题行
* @param headerRows 表头行
* @param pojoClass pojo类型
* @param <T>
* @return
*/
public static <T> List<T> importExcel(InputStream inputStream, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws IOException {
if (inputStream == null) {
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
params.setSaveUrl("/excel/");
// params.setNeedSave(true);
try {
return ExcelImportUtil.importExcel(inputStream, pojoClass, params);
} catch (NoSuchElementException e) {
throw new IOException("excel文件不能为空");
} catch (Exception e) {
throw new IOException(e.getMessage());
}
}