1- 关于excel下载
//excelUtil.js
import XLSX from 'xlsx';
function importExcel(file) {
// 获取上传的文件对象
const { files } = file.target;
// 通过FileReader对象读取文件
const fileReader = new FileReader();
fileReader.onload = event => {
try {
const { result } = event.target;
// 以二进制流方式读取得到整份excel表格对象
const workbook = XLSX.read(result, { type: 'binary' });
let data = []; // 存储获取到的数据
// 遍历每张工作表进行读取(这里默认只读取第一张表)
for (const sheet in workbook.Sheets) {
if (workbook.Sheets.hasOwnProperty(sheet)) {
// 利用 sheet_to_json 方法将 excel 转成 json 数据
data = data.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
// break; // 如果只取第一张表,就取消注释这行
}
}
} catch (e) {
// 这里可以抛出文件类型错误不正确的相关提示
// console.log('文件类型不正确');
return null;
}
};
// 以二进制方式打开文件
fileReader.readAsBinaryString(files[0]);
}
function exportExcel(headers, data, fileName = 'xxx表.xlsx') {
const _headers = headers
.map((item, i) => Object.assign({}, { key: item.key, title: item.title, position: String.fromCharCode(65 + i) + 1 }))
.reduce((prev, next) => Object.assign({}, prev, { [next.position]: { key: next.key, v: next.title } }), {});
const _data = data
.map((item, i) => headers.map((key, j) => Object.assign({}, { content: item[key.key], position: String.fromCharCode(65 + j) + (i + 2) })))
// 对刚才的结果进行降维处理(二维数组变成一维数组)
.reduce((prev, next) => prev.concat(next))
// 转换成 worksheet 需要的结构
.reduce((prev, next) => Object.assign({}, prev, { [next.position]: { v: next.content } }), {});
// 合并 headers 和 data
const output = Object.assign({}, _headers, _data);
// 获取所有单元格的位置
const outputPos = Object.keys(output);
// 计算出范围 ,["A1",..., "H2"]
const ref = `${outputPos[0]}:${outputPos[outputPos.length - 1]}`;
// 构建 workbook 对象
const wb = {
SheetNames: ['mySheet'],
Sheets: {
mySheet: Object.assign(
{},
output,
{
'!ref': ref,
'!cols': [{ wpx: 45 }, { wpx: 100 }, { wpx: 200 }, { wpx: 80 }, { wpx: 150 }, { wpx: 100 }, { wpx: 300 }, { wpx: 300 }],
},
),
},
};
// 导出 Excel
XLSX.writeFile(wb, fileName);
}
function saveJSON(data, filename) {
if (!data) {
return;
}
if (!filename) filename = 'json.json'
if (typeof data === 'object') {
data = JSON.stringify(data, undefined, 4)
}
const blob = new Blob([data], { type: 'text/json' });
const e = document.createEvent('MouseEvents');
const a = document.createElement('a');
a.download = filename;
a.href = window.URL.createObjectURL(blob);
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':');
e.initMouseEvent('click', true, false);
a.dispatchEvent(e);
}
//支持大批量数据导出,目前测试15万行 30列通过,导出时间约为6秒
function toLargerCSV(headers, data, fileName = 'xxx表.csv') {
//CSV格式可以自己设定,适用MySQL导入或者excel打开。
//由于Excel单元格对于数字只支持15位,且首位为0会舍弃 建议用 =“数值”
let str = '';
str += `${headers.map(item => `${item?.title}`)}`;
str += '\n';
data.map(item => {
const arr = [];
headers.map(ele => {
arr.push(item[ele?.key])
})
// str += `${Object.values(item || {}).join(',')},\n`
str += `${arr.join(',')},\n`
})
let blob = new Blob([str], { type: 'text/plain;charset=utf-8' });
//解决中文乱码问题
blob = new Blob([String.fromCharCode(0xFEFF), blob], { type: blob.type });
const object_url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = object_url;
link.download = fileName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
//支持大批量数据导出,目前测试15万行 30列通过,导出时间约为6秒
function toLargerCSV(){
//CSV格式可以自己设定,适用MySQL导入或者excel打开。
//由于Excel单元格对于数字只支持15位,且首位为0会舍弃 建议用 =“数值”
var str = '行号,内容,题目,标题\n';
for(let i=0;i<100000;i++){
str += i.toString()+',1234567890123456789\t,张三李四王五赵六,bbbb,\n'
}
var blob = new Blob([str], {type: "text/plain;charset=utf-8"});
//解决中文乱码问题
blob = new Blob([String.fromCharCode(0xFEFF), blob], {type: blob.type});
object_url = window.URL.createObjectURL(blob);
var link = document.createElement("a");
link.href = object_url;
link.download = "导出.csv";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
export default { importExcel, exportExcel, saveJSON, toLargerCSV };