前言
Vue实现导出Excel,所需要的数据时通过异步请求后台获取,
后台将查询到的数据返回给前端,然后前端实现导出Excel。
现在来看怎样请求后端并获取数据的部分。
前端
点击按钮调用方法
<el-button type="primary" class="mt_0 ml_1em bg_gray_777" @click="exportClick()">导出账单</el-button>
请求后台的方法
//报表导出前的查询
exportClick(){
this.loading = true;
exportMerchantBill(this.billForm).then(response => {
debugger;
this.loading = false;
const data = response.data;
this.exportList = data;
//开始执行导出方法
this.export2Excel()
}).catch(error => {
debugger;
this.loading = false
console.log(error)
})
},
在data中的billForm:
billForm: {
startDate: '',
endDate: '',
currentPage: 1,
pageSize: 10,
},
引入 exportMerchantBill
import { searchMerchantBillPageResult,exportMerchantBill} from '@/api/account'
发起请求的方法
export function exportMerchantBill(data) {
return fetch({
headers: {"Content-Type": "application/json"},
url: '/merchant/bill/exportMerchantBill',
method: 'post',
data: {
billForm: data
}
})
}
后台
action
@Controller
@RequestMapping("merchant/bill")
public class MerchantBillSerialAction {
private BusMerchantBillserialService service;
@Autowired
public void setServce(BusMerchantBillserialService service) {
this.service = service;
}
@ResponseBody
@RequestMapping("/exportMerchantBill")
public Json<List<BusMerchantBillserialExt>> exportMerchantBill(@RequestBody Map map){
try {
ParamBean reqJson = JSON.parseObject(JSON.toJSONString(map.get("billForm")),
ParamBean.class);
reqJson.setCurrentPage(null);
reqJson.setPageSize(null);
// 获取当前用户
JwtUserModel userModel = ResourceUtil.getCurrentUser();
PageResult<BusMerchantBillserialExt> pageResult = new PageResult<BusMerchantBillserialExt>();
Map<String,Object> param = pageResult.getParam();
if(reqJson.getStartDate()!=null) {
reqJson.setStartDateStr(DateConvert.formatDateToString(reqJson.getStartDate(), DateStyle.YYYY_MM_DD) +" 00:00:00" );
param.put("startTime", reqJson.getStartDateStr());
}
if(reqJson.getEndDate()!=null) {
reqJson.setEndDateStr(DateConvert.formatDateToString(reqJson.getEndDate(), DateStyle.YYYY_MM_DD) +" 23:59:59" );
param.put("endTime", reqJson.getEndDateStr());
}
param.put("merchantId", userModel.getUserId());
param.put("status",Constants.IS_DATA_STATUS);
param.put("orderField","recordTime");
param.put("orderDirection","desc");
pageResult.setParam(param);
List<BusMerchantBillserialExt> data= service.searchPageMerchantBillForExportByParam(param);
return new Json<List<BusMerchantBillserialExt>>().success(data);
} catch (Exception e) {
LogService.getInstance(this).error("查询账单信息失败",e);
return new Json<List<BusMerchantBillserialExt>>().fail();
}
}
serviceImpl
@Override
public List<BusMerchantBillserialExt> searchPageMerchantBillForExportByParam(Map<String, Object> param) {
if (!"".equals(param.get("orderField")))
{
param.put("orderColumn", param.get("orderField"));
}
param.put("orderTurn", param.get("orderDirection"));
List<BusMerchantBillserialExt> data = dao.getMerchantBillByParam(param);
return data;
}
相应的mapper以及model不再提供,这里只是展示大概的思想,具体代码要根据自己的业务去编写。