檔案導出:
要實作檔案導出功能,若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,
},