点击下载:xlsx.js
文档:https://docs.sheetjs.com/
纯前端导入excel代码:
const XLSX = require('../utils/xlsx.js') function importUser() { if(uni.getSystemInfoSync().platform === 'android'){ 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) { uni.$app.showToast('文件读取失败!') return } } }) } else { wx.chooseMessageFile({ count: 1, type: 'file', // 不要写,否则IOS无法识别 // 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) { uni.$app.showToast('文件读取失败!') return } } }) } } 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); if(!rawData || rawData.length === 0) { uni.$app.showToast('excel表格没有数据!') } else { const userList = [] rawData.forEach(item => { userList.push({ name: item['姓名'] ?? '', source: item['所属项目'] ?? '', mobilePhone: item['手机号'] ?? '', identityStr: item['身份类别'] ?? '', attr8: item['身份证号'] ?? '', attr5: item['保安证号'] ?? '' }) }) if(userList.length) { uni.$app.ajax({ api: uni.$api.impexcel(), data: { id: props.detail.id, userList } }).then(res => { uni.$app.hideLoading() if(res.status === 200) { uni.$app.showToast('导入成功!') } else { uni.$app.showToast(res.message) } }) } } }
纯前端导出excel代码:
const XLSX = require('../utils/xlsx.js') Page({ exportData() { // 数据源 const data = [{ code: 1, name: 'A', }, { code: 2, name: 'B', }, { code: 3, name: 'C', }, { code: 4, name: 'D', }] // 构建一个表的数据 let sheet = [] let title = ['序号', '姓名'] sheet.push(title) data.forEach(item => { let rowcontent = [] rowcontent.push(item.code) rowcontent.push(item.name) sheet.push(rowcontent) }) // XLSX插件使用 var ws = XLSX.utils.aoa_to_sheet(sheet); var wb = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(wb, ws, "用户表"); var fileData = XLSX.write(wb, { bookType: "xlsx", type: 'base64' }); let filePath = `${wx.env.USER_DATA_PATH}/用户表.xlsx` // 写文件 const fs = wx.getFileSystemManager() fs.writeFile({ filePath: filePath, data: fileData, encoding: 'base64', bookSST: true, success(res) { console.log(res) const sysInfo = wx.getSystemInfoSync() // 导出 if (sysInfo.platform.toLowerCase().indexOf('windows') >= 0) { // 电脑PC端导出 wx.saveFileToDisk({ filePath: filePath, success(res) { console.log(res) }, fail(res) { console.error(res) util.tips("导出失败") } }) } else { // 手机端导出 // 打开文档 wx.openDocument({ filePath: filePath, showMenu: true, success: function (res) { console.log('打开文档成功') }, fail: console.error }) } }, fail(res) { if (res.errMsg.indexOf('locked')) { wx.showModal({ title: '提示', content: '文档已打开,请先关闭', }) } } }) } })