前端-------------------------------------------------------------------------------------------------------
/* 导出 */
handleExportXls(fileName){
console.log("111111111111111111111111")
if(!fileName || typeof fileName != "string"){
fileName = "导出文件"
}
let param = this.getQueryParams();
if(this.selectedRowKeys && this.selectedRowKeys.length>0){
param['selections'] = this.selectedRowKeys.join(",")
}
console.log("导出参数",param)
downFile(this.url.exportXlsUrl,param).then((data)=>{
if (!data) {
this.$message.warning("文件下载失败")
return
}
if (typeof window.navigator.msSaveBlob !== 'undefined') {
window.navigator.msSaveBlob(new Blob([data],{type: 'application/vnd.ms-excel'}), fileName+'.xls')
}else{
let url = window.URL.createObjectURL(new Blob([data],{type: 'application/vnd.ms-excel'}))
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', fileName+'.xls')
document.body.appendChild(link)
link.click()
document.body.removeChild(link); //下载完成移除元素
window.URL.revokeObjectURL(url); //释放掉blob对象
}
})
},
// 下载模板
exportTemplate(fileName){
if(!fileName || typeof fileName != "string"){
fileName = "导出文件"
}
downFile(this.url.exportTemplate).then((data)=>{
if (!data) {
this.$message.warning("文件下载失败")
return
}
if (typeof window.navigator.msSaveBlob !== 'undefined') {
window.navigator.msSaveBlob(new Blob([data],{type: 'application/vnd.ms-excel'}), fileName+'.xls')
}else{
let url = window.URL.createObjectURL(new Blob([data],{type: 'application/vnd.ms-excel'}))
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', fileName+'.xls')
document.body.appendChild(link)
link.click()
document.body.removeChild(link); //下载完成移除元素
window.URL.revokeObjectURL(url); //释放掉blob对象
}
})
},
/* 导入 */
handleImportExcel(info){
if (info.file.status !== 'uploading') {
console.log(info.file, info.fileList);
}
if (info.file.status === 'done') {
if (info.file.response.success) {
// this.$message.success(`${info.file.name} 文件上传成功`);
if (info.file.response.code === 201) {
let { message, result: { msg, fileUrl, fileName } } = info.file.response
let href = window._CONFIG['domianURL'] + fileUrl
this.$warning({
title: message,
content: (<div>
<span>{msg}</span><br/>
<span>具体详情请 <a href={href} target="_blank" download={fileName}>点击下载</a> </span>
</div>
)
})
} else {
this.$message.success(info.file.response.message || `${info.file.name} 文件上传成功`)
}
this.loadData()
} else {
this.$message.error(`${info.file.name} ${info.file.response.message}.`);
}
} else if (info.file.status === 'error') {
if (info.file.response.status === 500) {
let data = info.file.response
const token = Vue.ls.get(ACCESS_TOKEN)
if (token && data.message.includes("Token失效")) {
Modal.error({
title: '登录已过期',
content: '很抱歉,登录已过期,请重新登录',
okText: '重新登录',
mask: false,
onOk: () => {
store.dispatch('Logout').then(() => {
Vue.ls.remove(ACCESS_TOKEN)
window.location.reload();
})
}
})
}
} else {
this.$message.error(`文件上传失败: ${info.file.msg} `);
}
}
},
后端-------------------------------------------------------------------------------------------------------------------
/**
* 通过excel导入数据
*
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response)throws IOException {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
// 错误信息
List<String> errorMessage = new ArrayList<>();
AtomicInteger successLines = new AtomicInteger();
AtomicInteger errorLines = new AtomicInteger();
for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
MultipartFile file = entity.getValue();// 获取上传文件对象
ImportParams params = new ImportParams();
params.setTitleRows(2);
params.setHeadRows(0);
params.setNeedSave(true);
try {
List<Customer> listCustomers = ExcelImportUtil.importExcel(file.getInputStream(), Customer.class, params);
listCustomers.forEach(c->{
if(StringUtil.isBlank(c.getCustomerName())){
errorMessage.add("发生异常:第"+((errorLines.get()/1)+1)+"行客户名称为空");
errorLines.getAndIncrement();
return;
}else if(StringUtil.isBlank(c.getCustomerType())){
errorMessage.add("发生异常:第"+((errorLines.get()/1)+1)+"行客户类别为空");
errorLines.getAndIncrement();
return;
}else if( StringUtil.isBlank(c.getIndustry())){
errorMessage.add("发生异常:第"+((errorLines.get()/1)+1)+"行客户行业为空");
errorLines.getAndIncrement();
return;
}
List<Map<String, Object>> maps = sysDictService.queryDictByDictCode("customer_category", c.getCustomerType());
if(maps!=null && maps.size()>0){
c.setCustomerType(maps.get(0).get("itemValue").toString());
}
List<Map<String, Object>> maps1 = sysDictService.queryDictByDictCode("customer_industry", c.getIndustry());
if(maps1!=null && maps1.size()>0){
c.setIndustry(maps1.get(0).get("itemValue").toString());
}
customerService.save(c);
successLines.getAndIncrement();
}
);
} catch (Exception e) {
errorMessage.add("发生异常:" + e.getMessage());
log.error(e.getMessage(), e);
} finally {
try {
file.getInputStream().close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
return ImportExcelUtil.imporReturnRes(errorLines.get(), successLines.get(),errorMessage);
}
/**
* 导出excel
*
* @param request
* @param customer
*/
@RequestMapping(value = "/exportXls")
public ModelAndView exportXls(Customer customer, HttpServletRequest request) {
// Step.1 组装查询条件
QueryWrapper<Customer> queryWrapper = QueryGenerator.initQueryWrapper(customer, request.getParameterMap());
//Step.2 AutoPoi 导出Excel
ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
//update-begin--Author:kangxiaolin Date:20180825 for:[03]客户导出,如果选择数据则只导出相关数据--------------------
String selections = request.getParameter("selections");
if(!oConvertUtils.isEmpty(selections)){
queryWrapper.in("id",selections.split(","));
}
//update-end--Author:kangxiaolin Date:20180825 for:[03]客户导出,如果选择数据则只导出相关数据----------------------
List<DictModel> categorys = sysDictService.getDictItems("customer_category");
List<DictModel> industrys = sysDictService.getDictItems("customer_industry");
List<Customer> pageList = customerService.list(queryWrapper);
pageList.forEach(c->{
if(categorys!=null && categorys.size()>0){
categorys.forEach(cat->{
if(cat.getValue().equals(c.getCustomerType())){
c.setCustomerType(cat.getTitle());
}
});
}
if(industrys!=null && industrys.size()>0){
industrys.forEach(ind->{
if(ind.getValue().equals(c.getIndustry())){
c.setIndustry(ind.getTitle());
}
});
}
});
//导出文件名称
mv.addObject(NormalExcelConstants.FILE_NAME, "客户列表");
mv.addObject(NormalExcelConstants.CLASS, Customer.class);
LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
ExportParams exportParams = new ExportParams("客户列表数据", "导出人:"+user.getRealname(), "导出信息");
mv.addObject(NormalExcelConstants.PARAMS, exportParams);
mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
return mv;
}
/**
* 导出模板
*
* @param
*/
@RequestMapping(value = "/exportTemplate")
public ModelAndView exportTemplate() {
List<Customer> pageList = new ArrayList<>();
//Step.2 AutoPoi 导出Excel
ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
//导出文件名称
mv.addObject(NormalExcelConstants.FILE_NAME, "客户列表导入模板");
mv.addObject(NormalExcelConstants.CLASS, Customer.class);
LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
ExportParams exportParams = new ExportParams("客户列表数据", "导出人:"+user.getRealname(), "导出信息");
mv.addObject(NormalExcelConstants.PARAMS, exportParams);
mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
return mv;
}