需求:项目中已存在“导出”功能,现在给未做导出功能的页面增加导出功能。
效果:可根据查询条件进行导出,可选定部分指定列表字段进行导出。
import {message} from 'antd'; // 导出成功or失败的提示
import FileSave from 'file-saver'; // 文件保存
import ExcelExporter from 'widget'; // excel导出
// 初始化
exportVisible: false, // 导出弹窗
exportColumns:[ // 导出列
{title:'代码',dataIndex:'code'},
{title:'名称',dataIndex:'name'},
{}
],
// 导出功能
confirmExport = params =>{
const { searchParams } = this.state;
const hide = message.loading(this.$t('importer.spanned.file'));
Service.exportWay(params ,searchParams ) // 根据查询条件导出
.then(res=>{
if(res.status ===200 ){
message.success(this.$t('importer.view.search.exportSuccess'));
const fileName = res.headers['content-disposition'].split('filename=')[1];
const f = new Blod([res.data]);
FileSaver.saveAs(f, decodeURIComponent(fileName));
hide();
}
}).catch(()=>{
message.error(this.$t('importer.download.error.info'));
hide();
});
};
render(){
const { exportVisible, exportColumns } = this.state;
return(
...
<Button type="primary" onClick={()=>this.setState({ exportVisible: true }) }>
{this.$t({ id: '导出' })}
</Button>
<ExcelExporter
visible={exportVisible}
onOk={this.confirmExport}
columns={exportColumns}
canCheckVersion={false}
fileName='导出的文件名'
onCancel={()=>this.setState({ exportVisible: false }) }
excelItem="PREPAYMENT_FINANCIAL_QUERY"
/>
...
)
}
// service.js 后台接口
exportWay(params ,searchParams){
let url = `${config.budgetUrl}/api/budget/groups/export?`
for(let searchName in searchParams){
url += searchParams[searchName ] ? `&${searchName}=${searchParams[searchName ]}` : '';
}
return httpFetch.post(url, params, {}, { 'responseType: 'arraybuffer' });
}