前端:
<el-upload
v-loading="importOpenLoading"
ref="renewUpload"
:show-file-list="false"
:limit="1"
:on-success="renewImportExcelSuccess"
:before-upload="renewBefUpUserFile"
:file-list="renewUpUserfileList"
accept=".xlsx"
class="filter-item upload-demo"
action=""
size="mini"
multiple>
<el-button v-permission="['sys:xdsdtu:excleRenew']" size="mini" type="primary"><i class="fa fa-upload fontMoveLeft" aria-hidden="true"/>导入续费iccid
</el-button>
</el-upload>
method:
renewImportExcelSuccess(){
// 文件上传成功后处理
this.importOpenLoading = false
// 删除文件
this.$refs.renewUpload.clearFiles()
},
renewBefUpUserFile(file){
this.importOpenLoading = true
const self = this
var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
const extensionxlsx = testmsg === 'xlsx'
// let extensionxls = testmsg ==='xls';
if (extensionxlsx) {
const formData = new FormData()
formData.append("file", file)
importExcel(formData).then(res => {
const link = document.createElement('a')
const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
link.style.display = 'none'
link.href = URL.createObjectURL(blob)
// link.download = res.headers['content-disposition'] //下载后文件名
link.download = '续费iccid.xlsx' // 下载的文件名
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
this.importOpenLoading = false
}).catch(function() {
this.importOpenLoading = false
ElementMessage(self, 'error', '下载异常')
})
} else {
self.ElementMessage('info', '只能上传xlsx类型文件')
return false
}
},
js:
import request from '@/utils/request'
export function importExcel(data) {
let config = {
headers: {
"Content-Type": "multipart/form-data"
}
}
return request({
url: '/handle/excel/dtu',
method: 'POST',
data: data,
type: 'downloadExcel',
headers: config,
})
}
后端:
@RequestMapping(value = "/**", method = RequestMethod.POST)
@ResponseBody
public void importExcel(@RequestParam(value = "file") MultipartFile file, HttpServletResponse response) throws IOException {
List<ExcelVo> excelVoList = EasyExcelUtil.readExcelWithModelbefor(file, ExcelVo.class);//使用模板接收@RequestMapping(value = "/importUserExcel", method = RequestMethod.POST)
List<ExportVo> list = new ArrayList<>();
if (CollectionUtil.isNotEmpty(excelVoList)) {
ExcelUtil.resExcel(list,response,"过期设备",ExportVo.class);
}
}
public static <T> void resExcel(List<T> lsit, HttpServletResponse response, String resFileName, Class<T> clz){
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
String fileName = null;
try {
fileName = URLEncoder.encode(resFileName, "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
EasyExcel.write(response.getOutputStream(), clz).sheet("模板").doWrite(lsit);
} catch (IOException e) {
log.error("导出excel异常,文件名: " + fileName, e);
}
}
注:使用的alibaba的EasyExcel 导出集合实体类 extends BaseRowModel