1. 程式人生 > 實用技巧 >uniapp匯入匯出Excel

uniapp匯入匯出Excel

眾所周知,uniapp作為跨端利器,有諸多限制,其中之一便是vue頁面不支援傳統網頁的dom、bom、blob等物件。

所以,百度上那些所謂的匯入匯出excel的方法,大部分都用不了,比如xlsx那個外掛,雖然很多方法在vue裡不支援,但解析資料等不包含dom那些物件的方法可以考慮下。

外掛git:https://github.com/SheetJS/js-xlsx

話不多說,經過一段時間的摸索,uniapp中,app端匯入匯出,實現方案如下:

匯出Excel,走的是系統IO流,程式碼如下:dateUtil.js的程式碼點這裡

<template>
    <view class="content"
> <view class="top_box">{{title}}</view> <view class="btn_cube" @click="tableToExcel">匯出一個表來看</view> <view class="tip">tips:合併什麼的可以直接用table標籤相關的行內屬性合併,如colspan、rowspan</view> <view class="tip">tips:建立目錄時,一個大目錄,下面再有一級年月的目錄,方便到時候讀取目錄</
view> <view class="tip">{{successTip}}</view> </view> </template> <script> import {formatNumber,formatDateThis,getUnixTime} from "@/common/util/dateUtil.js" var that; export default { components:{ }, data() {
return { title:"app端匯出excel", successTip:"" } }, onLoad() { that = this; }, methods: { tableToExcel() { //要匯出的json資料 const jsonData = [{ name: '測試資料', phone: '123456', email: '[email protected]' } ] //列標題 let worksheet = "sheet1"; let str = '<tr><td>姓名</td><td>電話</td><td>郵箱</td></tr>'; //迴圈遍歷,每行加入tr標籤,每個單元格加td標籤 for (let i = 0; i < jsonData.length; i++) { str += '<tr>'; for (let item in jsonData[i]) { //增加\t為了不讓表格顯示科學計數法或者其他格式 str += `<td>${ jsonData[i][item] + '\t'}</td>`; } str += '</tr>'; } //下載的表格模板資料 let template = `<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"> <head><!--[if gte mso 9]><xml encoding="UTF-8"><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet> <x:Name>${worksheet}</x:Name> <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet> </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--> </head><body><table>${str}</table></body></html>`; //下載模板 exportFile(template); } } } // 匯出檔案到手機 fileData:要寫入到檔案的資料,返回引數為文件路徑 function exportFile (fileData,documentName="專案Excel檔案") { /* PRIVATE_DOC: 應用私有文件目錄常量 PUBLIC_DOCUMENTS: 程式公用文件目錄常量 */ plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENTS, function(fs) { let rootObj = fs.root; let fullPath = rootObj.fullPath; // let reader = rootObj.createReader(); // console.log(reader); // reader.readEntries((res)=>{ // console.log(res); //這裡拿到了該目錄下所有直接檔案和目錄 // },(err)=>{console.log(err);}) console.log("開始匯出資料********"); // 建立資料夾 rootObj.getDirectory(documentName, { create: true }, function(dirEntry) { //獲取當前的年月繼續建立資料夾 let date = new Date(); let year = date.getFullYear(); let month = date.getMonth() + 1; dirEntry.getDirectory(`${year}年${month}月`,{ create:true },function(dirEntry2){ // 建立檔案,防止重名 let fileName = "excel"+getUnixTime(formatDateThis(new Date())); console.log(fileName); dirEntry2.getFile(`${fileName}.xlsx`, { create: true }, function(fileEntry) { fileEntry.createWriter(function(writer) { writer.onwritestart = (e)=>{ uni.showLoading({ title:"正在匯出", mask:true }) } // /storage/emulated/0指的就是系統路徑 let pathStr = fullPath.replace("/storage/emulated/0",""); writer.onwrite = (e) => { // 成功匯出資料; uni.hideLoading(); setTimeout(()=>{ uni.showToast({ title:"成功匯出", icon:"success" }) that.successTip = `檔案位置:${pathStr}/${documentName}/${year}年${month}月`; },500) }; // 寫入內容; writer.write(fileData); }, function(e) { console.log(e.message); }); }); }) }); }); } </script>

至於匯入Excel,我這裡就不貼程式碼了,思路就是利用uniapp的web-view標籤,相當於是傳統網頁的做法,利用input標籤的file屬性,最後把解析到的值,傳遞迴vue頁面。

web-view相關閱讀:https://uniapp.dcloud.io/component/web-view

    uni.postMessage({
        data: {
            excelData: finalData
        }
    });

tips:手機上不比電腦,如果要除錯如上功能,建議下個辦公軟體,比如wps手機版,這樣找excel檔案就比較快。