前端使用XLSX.JS(SheetJS)导出

97 阅读1分钟
import * as XLSX from 'xlsx/xlsx.mjs'

// 最基本的导出
/**
 * 
 * @param { data 导出的数据 } 
 * @param { name 表格名字 不含xlsx }
 * @param { columns 列顺序 }
 * @param { titleMap 列标题映射对象 } 
 * @returns 
 */
function fn({ data, name, columns, titleMap }) {
    // 校验 data 如果不是数组或者 是空的 就直接返回
    if (!Array.isArray(data) || data.length <= 0) {
        return new Error("data应该是非空数组")
    }

    // 如果用户没有主动传columns, 就用data[0] 的所有Key作为默认顺序
    const headerKeys = Array.isArray(columns) && columns.length > 0 ? columns : Object.keys(data[0])

    // json_to_sheet 将 JSON 数据转换为工作表格式 header 选项指定列顺序(此时表头仍是原始键名)
    const ws = XLSX.utils.json_to_sheet(data, { header: headerKeys })

    // 遍历处理每一列的表头 r: 0 表示第一行(表头行) c: colIdx 表示当前列索引
    headerKeys.forEach((key, colIdx) => {
        const cellAddress = XLSX.utils.encode_cell({ r: 0, c: colIdx })
        ws[cellAddress].v = titleMap[key] || key
    })

    const wb = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(wb, ws, "Sheet1")
    XLSX.writeFile(wb, `${name}.xlsx`)
}

export default fn