import * as XLSX from "xlsx-js-style";

/**
 * 导出Excel表格
 * @param header 生成excel的表头 []
 * @param data 生成excel的内容 []
 * @param merges 生成excel的合并单元格
 * @param name 生成excel的文件名，如：abc.xlsx
 * */
export const exportExcel = (header, data, merges, name) => {
    const workbook = XLSX.utils.book_new();  // 创建一个工作表  
    const worksheet = XLSX.utils.aoa_to_sheet([header, ...data]);// 将工作表添加到工作簿 

    // 设置worksheet每列的最大宽度
    const colWidth = data.map(d => d.map(val => {
        let wch = 10;
        // 是否为中文
        if (val) wch = val.toString().split("").map(str => str.charCodeAt() > 255 && 2 || 1).reduce((p, v) => p + v);
        return { wch };
    }));
    // 以第一行为初始值
    let result = colWidth[0];
    for (let i = 1; i < colWidth.length; i++) {
        for (let j = 0; j < colWidth[i].length; j++) {
            if (result[j]["wch"] < colWidth[i][j]["wch"]) result[j]["wch"] = colWidth[i][j]["wch"];
        }
    }
    header.forEach((val, i) => {
        if (result[i]["wch"] < val.length * 2) result[i]["wch"] = val.length * 2;
    });
    worksheet["!cols"] = result;

    // 合并单元格
    worksheet["!merges"] = merges;

    // 设置居中
    for (let i in worksheet) {
        if (worksheet[i].v) worksheet[i].s = { alignment: { horizontal: "center", wrapText: true, vertical: "center" } };
    }
    XLSX.utils.book_append_sheet(workbook, worksheet);  // 生成Excel文件 
    XLSX.writeFile(workbook, name);
}