uniapp app端将JSON数据导出为Excel表格

uniapp yekong

依赖文件

function get_object_first_attribute(data) {
    for (var key in data)
        return data[key];
}

function myCache(key, value, seconds = 3600 * 24) {
    let nowTime = Date.parse(new Date()) / 1000;
    if (key && value) {
        let expire = nowTime + Number(seconds);
        uni.setStorageSync(key, JSON.stringify(value) + '|' + expire)
        console.log('已经把' + key + '存入缓存,过期时间为' + expire)
    } else if (key && !value) {
        let val = uni.getStorageSync(key);
        if (val) {
            // 缓存存在,判断是否过期
            let temp = val.split('|')
            if (!temp[1] || temp[1] <= nowTime) {
                uni.removeStorageSync(key)
                console.log(key + '缓存已失效')
                return '';
            } else {
                return JSON.parse(temp[0]);
            }
        }
    }

}
//日期转时间戳
function getUnixTime(dateStr) {
    var newstr = dateStr.replace(/-/g, '/');
    var date = new Date(newstr);
    var time_str = date.getTime().toString();
    return time_str.substr(0, 10);
}

//时间戳转日期,falg:true表示只要年月日,part: year month date
function toDate(number, flag, part) {
    var n = number;
    var date = new Date(parseInt(n) * 1000);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    if (flag) {
        if (part == "year") {
            return y;
        } else if (part == "month") {
            return m;
        } else if (part == "date") {
            return n;
        }
        return y + '-' + m + '-' + d;
    }
    return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
}

//判断两个日期时间戳相差多少天,参数为时间戳
function dateCompare(dateTimeStamp1, dateTimeStamp2) {
    var dayNum = 0;
    if (dateTimeStamp1 > dateTimeStamp2) {
        dayNum = Math.floor((dateTimeStamp1 - dateTimeStamp2) / 86400);
    } else {
        dayNum = Math.floor((dateTimeStamp2 - dateTimeStamp1) / 86400);
    }
    return dayNum;
}

//判断过去某个时间点到当前时间是否达到多少天,可以用来定期清理缓存
function datePassDays(dateTimeStamp, days) {
    var now = getUnixTime(formatDateThis(new Date()));
    var diffValue = now - dateTimeStamp;
    var limitTime = days * 86400;
    if (diffValue >= limitTime) {
        return true;
    }
    return false;
}

//当前日期加减天数,falg:true表示只要年月日
function mathChangeDate(date, method, days, flag) {
    //method:'+' || '-'
    //ios不解析带'-'的日期格式,要转成'/',不然Nan,切记
    var dateVal = date.replace(/-/g, '/');
    var timestamp = Date.parse(dateVal);
    if (method == '+') {
        timestamp = timestamp / 1000 + 24 * 60 * 60 * days;
    } else if (method == '-') {
        timestamp = timestamp / 1000 - 24 * 60 * 60 * days;
    }
    return toDate(timestamp, flag);
}

//时间戳转换具体时间描述(传入数值型时间戳)
function getDateDiff(dateTimeStamp) {
    var result = '';
    var minute = 1 * 60;
    var hour = minute * 60;
    var day = hour * 24;
    var halfamonth = day * 15;
    var month = day * 30;
    var now = getUnixTime(formatDateThis(new Date())); //有些特殊 不能使用 new Date()
    var diffValue = now - dateTimeStamp;
    if (diffValue < 0) {
        return;
    }
    var monthC = diffValue / month;
    var weekC = diffValue / (7 * day);
    var dayC = diffValue / day;
    var hourC = diffValue / hour;
    var minC = diffValue / minute;

    if (monthC >= 1) {
        result = "" + parseInt(monthC) + "月前";
    } else if (weekC >= 1) {
        result = "" + parseInt(weekC) + "周前";
    } else if (dayC >= 1) {
        result = "" + parseInt(dayC) + "天前";
    } else if (hourC >= 1) {
        result = "" + parseInt(hourC) + "小时前";
    } else if (minC >= 1) {
        result = "" + parseInt(minC) + "分钟前";
    } else
        result = "刚刚";
    return result;
};

//获取当前年份,月份, 例: getCurrentTime("year")
const getCurrentTime = (method, date = new Date()) => {
    if (method == "year") {
        return date.getFullYear();
    } else if (method == "month") {
        return date.getMonth() + 1;
    }
    return date;
}

//获取当前服务器时间,参数直接用 new Date() 就可以了
const formatDateThis = (date, lab = '-') => {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();
    const second = date.getSeconds();
    return [year, month, day].map(formatNumber).join(lab) + ' ' + [hour, minute, second].map(formatNumber).join(
        ':');
}

const formatTime = (date, lab = '-') => {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    return [year, month, day].map(formatNumber).join(lab);
}
const formatTimes = time => {
    const hour = time.getHours();
    const minute = time.getMinutes();
    const second = time.getSeconds();
    return [hour, minute, second].map(formatNumber).join(':');
}
//补0
const formatNumber = n => {
    n = n.toString();
    return n[1] ? n : '0' + n;
}

//比较两个时间大小(格式参考yyyy-mm-dd hh:mm:ss)
function compareTime(startTime, endTime) {
    //结束时间大于开始时间就是true  , 反之则为 false
    var sn = getUnixTime(startTime) * 1;
    var en = getUnixTime(endTime) * 1;
    if (en > sn) {
        return true;
    }
    return false;
}

export {
    get_object_first_attribute,
    myCache,
    dateCompare,
    getCurrentTime,
    getUnixTime,
    formatDateThis,
    formatTime,
    formatTimes,
    toDate,
    getDateDiff,
    mathChangeDate,
    compareTime,
    datePassDays
};

引入依赖和接口导出数据

    import {
        formatNumber,
        formatDateThis,
        getUnixTime
    } from "../../utils/utils.js"
    import {
        ebookexport
    } from '../../config/api.js'
export default {
        data() {
            return {
                
            }
        },
        methods: {
            getdata() {
                var that = this;
                ebookexport().then(res => {
                    console.log(res)
                    if (res.code == 1) {
                        that.list = res.data
                        that.tableToExcel(that.list)
                    }
                }).catch(err => {

                })
            },

            tableToExcel(data) {
                var that = this;
                //要导出的json数据
                const jsonData = data
                //列标题
                let worksheet = "sheet1";
                let str = '<tr><td>序号</td><td>类型</td><td>事项</td><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) => {
                                console.log(e)
                                console.log(123)
                                // 成功导出数据;
                                uni.hideLoading();
                                setTimeout(() => {
                                    uni.showToast({
                                        title: `导出成功`,
                                        icon: "success"
                                    })
                                    // that.successTip =
                                    //  `文件位置:${pathStr}/${documentName}/${year}年${month}月`;
                                }, 500)
                                uni.openDocument({
                                    filePath: e.target.fileName,
                                    fileType: 'xlsx',
                                    success: function(res) {
                                    }
                                })
                            };
                            // 写入内容;
                            writer.write(fileData);

                        }, function(e) {
                            console.log(e.message);
                        });
                    });
                })

            });

        });

    }

喜欢