前言
这里我们用到的是SheetJS
https://xlsx.nodejs.cn/docs/
安装
1 2
| npm rm --save xlsx npm i --save https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz
|
导出
基本
1
| <a-button size="small" @click="excelExportClick">下载模板</a-button>
|
TS
1 2 3 4 5 6 7 8 9 10 11
| import XLSX from 'xlsx'
function excelExportClick() { const workbook = XLSX.utils.book_new() const worksheet = XLSX.utils.json_to_sheet([{ "订单号": '', "快递号": '' }]) XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1') XLSX.writeFile(workbook, '批量发货模板.xlsx') }
|
设置表头别名
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| import XLSX from 'xlsx'
function exportClick() { const data = [ { id: 1, name: 'John', age: 30 }, { id: 2, name: 'Jane', age: 25 } ]
const header = ['用户ID', '姓名', '年龄']
const ws_data = [ header, ...data.map((item) => [item.id, item.name, item.age]) ]
const ws = XLSX.utils.aoa_to_sheet(ws_data)
const wb = XLSX.utils.book_new() XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
XLSX.writeFile(wb, 'export.xlsx') }
|
导入
1 2
| <label for="file_upload" class="custom_button">选择文件</label> <input type="file" id="file_upload" class="file_upload" @change="excelImportClick"
|
TS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| import XLSX from 'xlsx'
function excelImportClick(event: any) { const files = event.target.files if (files.length > 0) { let file = files[0] const reader = new FileReader() reader.onload = (e: any) => { event.target.value = '' const data = new Uint8Array(e.target.result) const workbook = XLSX.read(data, { type: 'array' }) const worksheet = workbook.Sheets[workbook.SheetNames[0]] const jsonData = XLSX.utils.sheet_to_json(worksheet) let txtArr = [] if (jsonData && jsonData.length > 0) { for (let i = 0; i < jsonData.length; i++) { let item: any = jsonData[i] txtArr.push(`${item['订单号']} ${item['快递号']}`) } } formState.orderCode = txtArr.join('\n') } reader.readAsArrayBuffer(file) } }
|
样式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| .custom_button { display: flex; align-items: center; justify-content: center; height: 24px; padding-left: 10px; padding-right: 10px; background-color: #fa7e31; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 14px; user-select: none; }
.file_upload { display: none; }
|