XLSX.JS
链接:https://github.com/SheetJS/sheetjs
下载dist目录下的xlsx.mini.min.js即可(根据开发需求可下载其他版本)
Uniapp可以将js文件放在@/common/js/目录下
日期 | 事项 | 支出 |
---|---|---|
2023-01-01 | 吃饭 | 300.00 |
2023-01-02 | 喝奶茶 | 28.00 |
2023-01-03 | 地铁 | 2.00 |
H5端(Uniapp)选取文件并获得binary数据
uni.chooseFile({
count: 1,
extension: ['.xls', '.xlsx'],
success: res => {
let reader = new FileReader();
reader.onload = e => {
const data = e.target.result
process(data) // data为binary数据
};
reader.readAsBinaryString(res.tempFiles[0]);
}
})
小程序端选取文件并获得binary数据
wx.chooseMessageFile({
count: 1,
type: 'file',
extension: ['.xls', '.xlsx'],
success: res => {
try {
const path = res.tempFiles[0].path
const fs = wx.getFileSystemManager()
const data = fs.readFileSync(path, 'binary') // data为binary数据
process(data)
} catch (e) {
console.error(e)
uni.showModal({
title: '提示',
content: "文件读取失败",
showCancel: false
})
return
}
}
})
import XLSX from '@/common/js/xlsx.0.19.2.mini.min.js'
function process(data){
let workbook = XLSX.read(data, {
type: "binary"
});
const sheetName = workbook.SheetNames[0]
let sheet = workbook.Sheets[sheetName]
const options = {
raw: false // 如果不加raw:true的话日期会被读成数字,根据开发需求决定
}
const rawData = XLSX.utils.sheet_to_json(sheet, options);
// do something
}
此处得到的rawData结构为:
[
{
"日期": "2023-01-01",
"事项": "吃饭",
"支出": 300.00
},
{
"日期": "2023-01-02",
"事项": "喝奶茶",
"支出": 28.00
},
{
"日期": "2023-01-03",
"事项": "地铁",
"支出": 2.00
}
]
为了对齐数据采用二维数组格式
const data = [
[
'日期',
'事项',
'支出'
],
...Object.values(json_data)
]
const worksheet = XLSX.utils.aoa_to_sheet(data);
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, worksheet, '导出');
XLSX.writeFile(workbook, '导出.xlsx');
const fileData = XLSX.write(workbook, {
bookType: "xlsx",
type: 'base64'
});
const filePath = `${wx.env.USER_DATA_PATH}/导出.xlsx` // 文件名对应表名,多个表的情况可以自己测试
const fs = wx.getFileSystemManager()
fs.writeFile({
filePath: filePath,
data: fileData,
encoding: 'base64',
success: res => {
console.log(res)
const sysInfo = wx.getSystemInfoSync()
if (sysInfo.platform.toLowerCase().indexOf('windows') >= 0) {
wx.saveFileToDisk({
filePath: filePath,
success: console.log,
fail: console.error
})
} else {
wx.openDocument({
filePath: filePath,
showMenu: true, // 需要添加showMenu允许用户导出
success: console.log,
fail: console.error
})
}
},
fail: e => {
console.error(e)
if (e.errMsg.indexOf('locked')) {
wx.showModal({
title: '提示',
content: '文档已打开,请先关闭',
})
}
}
})