javascript 使用post提交数据并导出csv表格的方法示例
封装js导出表格的方法
function JSONToExcelConvertor(title, data, fileName) {
var CSV = '';
var row = "";
for (var i = 0; i < title.length; i++) {
if(title[i].title){
row += title[i].title + ',';
}
}
row = row.slice(0, -1);
CSV += row + '\r\n';
for (var i = 0; i < data.length; i++) {
var row = "";
for (var j = 0; j < title.length; j++) {
if(title[j].title){
row += '"' + (data[i][title[j].field] ? data[i][title[j].field] : "") + '"\t,';
}
}
row.slice(0, row.length - 1);
CSV += row + '\r\n';
}
if (CSV == '') {
alert("Invalid data");
return;
}
var fileName = fileName;
var uri = new Blob(['\ufeff' + CSV], {type:"text/csv"});
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(CSV, fileName + ".csv");
} else {
var link = document.createElement("a");
link.href = URL.createObjectURL(uri);
link.style = "visibility:hidden";
link.download = fileName + ".csv";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
post调用
function export_storemall_flow() {
let form = $("#store_form_flow").serialize();
var csrf = $("#_csrf").val();
var hq_activity_id = $("#hq_activity_id").val();
form += '&_csrf=' + csrf + '&hq_activity_id=' + hq_activity_id;
console.log('form', form);
$.post("/storemall/index/exportflow", form, function (e) {
if (e.status == 0) {
console.log(e);
data = e.data;
JSONToExcelConvertor(data.title, data.member_order_data, data.file_name);
}
}, 'json');
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/a0591790f5e0f48b2938aa065ef37058.png)