前台
element 自身就带了 导入的组件
<el-button size="small" v-if="isAuth('sys:holiday:holiday:exp')">批量导入</el-button>
<el-upload
class="upload-btn"
:action="uploadUrl"
accept=".xls, .xlsx"
:on-success="handleAvatarSuccess"
:on-progress="uploadProgress"
:on-error="handleUploadError"
:show-file-list="false"
>
这个组件 的action事件 然后里面有url。
这里我们来注意一下分一下excel 导入的具体实现。就是上传excel 表,然后指定路径上,上传成功后,读取excel 表,然后对数据进行处理 实现。
所以1发送url到文件上传地方
export default {
mixins: [requestTime],
data () {
return {
year: '',
uploadUrl: this.$http.adornUrl(
`/file/normalUpload?token=${
this.$cookie.get('token')}`
),
这里因为项目里多次会用到,就封装起来
@RequestMapping(path = "/normalUpload")
@ResponseBody
public R normalUpload(HttpServletRequest request, HttpServletResponse response) throws IOException {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload sfu = new ServletFileUpload(factory);
sfu.setHeaderEncoding("utf-8");
String savePath = this.fileUploadPathTemp;
String fileUrl = "";
String fielName = "";
try {
List<FileItem> items = sfu.parseRequest(request);
for (FileItem item : items) {
if (!item.isFormField()) {
fielName = item.getName();
String ext = fielName.substring(fielName.lastIndexOf("."));
String newFileName = UUID.randomUUID().toString();
File file = new File(savePath);
if (!file.exists()) {
file.mkdir();
}
fileUrl = savePath + File.separator + newFileName + ext;
File tempFile = new File(fileUrl);
FileUtils.copyInputStreamToFile(item.getInputStream(), tempFile);
}
}
} catch (FileUploadException e) {
throw new RRException("上传异常");
}
return R.ok().data("url", fileUrl).data("fielName", fielName);
}
当文件上传成功后,判断它的返回的值,然后到发起请求url的后台,对文件进行读取进行操作
//导入功能
handleAvatarSuccess (res, file) {
// this.uploadloading.close();
console.log(res);
if (res && res.code === 0) {
let fileUrl = res.data.url;
this.$http({
url: this.$http.adornUrl("/sys/holiday/imp"),
method: 'post',
data: this.$http.adornData({
fileUrl: fileUrl}, false)
}).then(({
data}) => {
if (data && data.code === 0) {
} else {
this.$errorMessage(data.msg)
}
})
this.$message({
message: '导入成功',
type: 'success',
duration: 1000,
onClose: () => {
this.getDataList()
}
})
} else {
this.$errorMessage(res.msg);
}
},
后台
@PostMapping("/imp")
public R imp(@RequestBody String params) throws Exception, IOException {
//接受前台从页面传来的文件地址参数
JSONObject json = JSON.parseObject(params);
//把他从json格式中取出来
String fileUrl = json.getString("fileUrl");
String config = "excel/sys/holiday-imp.xml";
ExcelImportor importor = new ExcelImportor(config, fileUrl, new FileInputStream(fileUrl));
//读取数据
ExcelImportData data = importor.loadData();
List<Map<String, Object>> list = (List<Map<String, Object>>) data.getDatas().get("holiday");
if (list != null && list.size() > Constant.IMPORT_MAX_NUM) {
throw new RRException("导入超过最大限制:" + Constant.IMPORT_MAX_NUM + "条");
}
//存放错误信息
List<Object> errDate = Lists.newArrayList();
//如果存在错误的数据日期,处理结束,显示错误信息【文件中存在无效的数据日期:xx,xx,xx】
for (Map<String, Object> stringObjectMap : list) {
//获取需要的数据日期
Object dataDate = stringObjectMap.get("dataDate");
try {
//统一格式把读取到数据日期转换成string
String date = dataDate.toString();
//然后转化成date
String format = DateUtils.format((Date) dataDate);
//存到读取数据的对象里 日期就ok了
stringObjectMap.put("dataDate",format);
} catch (Exception e) {
errDate.add(dataDate);
}
}
//错误的数据》0 抛出异常
if (errDate.size() > 0) {
throw new RRException(errDate.toString());
}
//把我读取到的数据转化成,于实体类一样对应的
List<SysHolidayEntity> sysHolidayEntities = JSON.parseArray(JSON.toJSONString(list), SysHolidayEntity.class);
sysHolidayService.save(sysHolidayEntities);
return R.ok();
}