文件导出:
要实现文件导出功能,若Controller代码如下:
@RequestMapping(value = "/exportCustomerList", method = RequestMethod.POST)
public void exportCustomerList(@RequestBody CustomerBase customerBase, HttpServletResponse response) {
XSSFWorkbook workbook = customerBaseService.genCustomerListExcel(customerBase);
try {
response.setHeader("content-Disposition", "attachment;filename="
+ URLEncoder.encode("客户基础信息.xlsx", "utf-8"));
OutputStream outputStream = response.getOutputStream();
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
} catch (IOException e) {
throw new ServiceException("excel写入失败");
}
}
则对应的前端导出代码如下:
const exportFile = () => {
return new Promise((resolve, reject) => {
const param = Object.assign({}, formState);
CustomerBaseApi.exportCustomerList(param)
.then((response) => {
const data = response.data;
if (data.size === 0) {
message.error("没有导出数据");
return;
}
const url = window.URL.createObjectURL(data);
const link = document.createElement("a");
link.style.display = "none";
link.href = url;
link.setAttribute("download", "客情基础信息.xls");
document.body.appendChild(link);
link.click();
})
.catch((error) => {
if (error.message !== "") {
message.error(error.message);
}
reject(error);
});
});
};
接口请求代码为:
exportCustomerList(data) {
return request({
url: "/customerbase/exportCustomerList",
method: "post",
data,
responseType: 'blob',
headers: { 'content-type': 'application/x-download;charset=utf-8' }
});
}
文件上传:
要实现文件上传功能,若Controller代码如下:
@RequestMapping(value = "/uploadExcel", method = RequestMethod.POST)
public Result uploadExcel(@RequestParam("file") MultipartFile file) {
if (file == null || file.isEmpty()) {
return ResultGenerator.genFailResult("上传文件为空");
}
String fileName = file.getOriginalFilename();
//判断是否为excel类型文件
if(!fileName.endsWith(".xls")&&!fileName.endsWith(".xlsx")){
return ResultGenerator.genFailResult("上传文件类型错误");
}
FileInputStream fis = null;
Workbook wookbook = null;
// 判断excel版本
Boolean isExcel2003 = fileName.toLowerCase().endsWith("xls")?true:false;
try {
//获取一个绝对地址的流
fis = (FileInputStream) file.getInputStream();
if(isExcel2003){
wookbook = new HSSFWorkbook(fis);
}else{
wookbook = new XSSFWorkbook(fis);
}
//得到一个工作表
Sheet sheet = wookbook.getSheetAt(0);
return batchInsert(sheet);
}catch(Exception e){
if (fis != null) {
try {
fis.close();
} catch (IOException e1) {
logger.error("关闭文件流异常");
}
}
logger.error("uploadExcel exception", e);
return ResultGenerator.genFailResult("文件上传失败");
}
}
则对应的前端上传代码如下:
<a-upload
v-model:file-list="fileList"
name="file"
:headers="headers"
:action="url"
:before-upload="beforeUpload"
:showUploadList="false"
@change="handleChange"
>
<a-button type="primary" style="margin-left: 8px">
<upload-outlined></upload-outlined>
上传文件
</a-button>
</a-upload>
JS代码如下:
const url = ref("");
const beforeUpload = (file) => {
url.value =
import.meta.env.VITE_APP_BASE_API +
"/customeranalyse/uploadExcel?fileName=" +
file.name;
};
const fileList = ref([]);
const handleChange = (info) => {
if (info.file.status !== "uploading") {
console.log(info.file, info.fileList);
}
if (info.file.status === "done") {
console.log("info", info);
if (info.file.response.code == 200) {
message.success(`${info.file.name}上传成功`);
} else {
message.error(info.file.response.message);
}
} else if (info.file.status === "error") {
message.error(`${info.file.name}上传失败`);
}
};
headers: {
Authorization: getToken(),
"trace-id": uuid.v1(),
"trace-user": store.getters.userid,
},