add:仓储管理出入库单据增加导出明细到excel

This commit is contained in:
zhaoyf
2026-10-31 15:53:39 +08:00
parent 46d922d7e3
commit 127cb06847
3 changed files with 205 additions and 16 deletions

View File

@@ -0,0 +1,47 @@
import XLSX from 'xlsx'
/**
* 生成文件名中的时间戳,如 20261031_152919
*/
export function formatExportTime(date) {
const pad = value => String(value).padStart(2, '0')
return date.getFullYear() + pad(date.getMonth() + 1) + pad(date.getDate()) + '_' +
pad(date.getHours()) + pad(date.getMinutes()) + pad(date.getSeconds())
}
/**
* 将数据按列定义导出为 excel 文件
*
* @param {Object} options
* @param {Array} options.columns 列定义 [{ label, prop, width, value }],value 为可选的自定义取值函数
* @param {Array} options.rows 数据行
* @param {String} options.sheetName sheet 名称
* @param {String} options.fileName 文件名(不含时间戳和后缀)
*/
export function exportRowsToExcel({ columns, rows, sheetName = '明细', fileName = '明细' }) {
if (!columns || !columns.length) {
throw new Error('未定义导出列')
}
const header = columns.map(col => col.label)
const body = rows.map(row => columns.map(col => {
const value = typeof col.value === 'function' ? col.value(row) : row[col.prop]
if (value === null || value === undefined) {
return ''
}
return value
}))
const sheet = XLSX.utils.aoa_to_sheet([header].concat(body))
sheet['!cols'] = columns.map(col => ({ wch: col.width || 14 }))
if (body.length) {
sheet['!autofilter'] = {
ref: XLSX.utils.encode_range({
s: { r: 0, c: 0 },
e: { r: body.length, c: header.length - 1 }
})
}
}
const workbook = XLSX.utils.book_new()
XLSX.utils.book_append_sheet(workbook, sheet, sheetName)
XLSX.writeFile(workbook, fileName + '_' + formatExportTime(new Date()) + '.xlsx')
return body.length
}