sc
This commit is contained in:
@@ -247,3 +247,56 @@ export const exportTableWithVue = (domId: any, fileName: String) => {
|
||||
return wbout
|
||||
// });
|
||||
}
|
||||
|
||||
/**
|
||||
* 数组数据导出为 Excel
|
||||
* @param {Array} data 要导出的数组数据(对象数组,如 [{name: '张三', age: 18}, ...])
|
||||
* @param {String} fileName 导出的文件名(不含 .xlsx 后缀)
|
||||
* @param {Array} header 自定义表头映射(可选,格式:[{key: 'name', title: '姓名'}, ...])
|
||||
* 若不传入,默认使用数据对象的 key 作为表头
|
||||
*/
|
||||
export const exportArrayToExcel = function (data: any[], fileName: String, header: any) {
|
||||
// 处理表头映射
|
||||
const worksheetData = []
|
||||
let headerKeys = [] // 数据对象的 key 集合
|
||||
let headerTitles = [] // 表头显示文本
|
||||
|
||||
if (header && header.length > 0) {
|
||||
// 使用自定义表头
|
||||
headerKeys = header.map((item) => item.key)
|
||||
headerTitles = header.map((item) => item.title)
|
||||
worksheetData.push(headerTitles) // 加入表头行
|
||||
} else {
|
||||
// 自动生成表头(使用数据中第一个对象的 key)
|
||||
if (data.length === 0) {
|
||||
console.warn('导出数据为空')
|
||||
return
|
||||
}
|
||||
headerKeys = Object.keys(data[0])
|
||||
headerTitles = headerKeys // 表头默认用 key
|
||||
worksheetData.push(headerTitles) // 加入表头行
|
||||
}
|
||||
|
||||
// 处理数据行(按表头 key 顺序提取数据)
|
||||
data.forEach((item) => {
|
||||
const row = headerKeys.map((key) => {
|
||||
// 处理特殊类型(如日期对象转为字符串)
|
||||
if (item[key] instanceof Date) {
|
||||
return item[key].toLocaleString()
|
||||
}
|
||||
// 其他类型直接转为字符串(避免 undefined 显示)
|
||||
return item[key] !== undefined ? String(item[key]) : ''
|
||||
})
|
||||
worksheetData.push(row)
|
||||
})
|
||||
|
||||
// 创建工作簿和工作表
|
||||
const ws = XLSX.utils.aoa_to_sheet(worksheetData) // 数组转工作表
|
||||
const wb = XLSX.utils.book_new() // 创建工作簿
|
||||
XLSX.utils.book_append_sheet(wb, ws, 'Sheet1') // 工作表命名为 Sheet1
|
||||
|
||||
// 生成二进制文件并下载
|
||||
const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
|
||||
const blob = new Blob([excelBuffer], { type: 'application/octet-stream' })
|
||||
saveAs(blob, `${fileName}.xlsx`) // 保存文件
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user