2-json数组对象导出为.csv文件,下载导出成支付宝交易记录明细

449 阅读1分钟

ExcelJsonDownload.vue组件

<template>
    <div class="select-excel">
        <el-button :loading="downloadLoading" @click="handleDownload" v-bind="$attrs" v-on="$listeners">
            <slot>Export Selected Items</slot>
        </el-button>
    </div>
</template>
<script>
import formatStrParse from './formatStrParse';

export default {
    name: 'select-excel',
    props: {
        // 导出的文件名称
        filename: {
            type: String,
            default: 'download-excel',
            required: false
        },
        // 文件后缀
        bookType: {
            type: String,
            default: 'csv'
        },
        // 导出的数据
        data: {
            type: Array,
            default: () => [],
            required: true
        },
        // 导出的表格表头
        tHeader: {
            type: Array,
            default: () => [],
            required: true
        },
        // 导出Json有哪些字段,需要使用它来替换成tHeader中的字段
        filterVal: {
            type: Array,
            default: () => [],
            required: true
        },
        // 表格JSON内容的前置内容
        beforeData: {
            type: Array,
            default: () => [],
            // 数据必须为二维数组
            validator: value => {
                return Array.isArray(value) && value.every(i => Array.isArray(i));
            }
        },
        // 表格JSON内容的后置内容
        afterData: {
            type: Array,
            default: () => [],
            validator: value => {
                return Array.isArray(value) && value.every(i => Array.isArray(i));
            }
        }
    },
    data() {
        return {
            downloadLoading: false
        };
    },
    methods: {
        handleDownload(event) {
            this.$emit('click', event);
            this.downloadLoading = true;
            import('@/vendor/Export2Excel').then(excel => {
                // const tHeader = ['Id', 'Title', 'Author', 'Readings', 'Date'];
                // const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time'];
                const tHeader = [...this.tHeader];
                const filterVal = [...this.filterVal];
                const multipleSelection = [...this.data]; // 需要导出的数据

                const data = this.formatJson(filterVal, multipleSelection);

                // let beforeData = [
                //     ['支付宝交易记录明细查询'],
                //     ['账号:[18230275891]'],
                //     ['起始日期:[2020-10-22 00:00:00]   终止日期:[2020-10-28 16:23:09]'],
                //     ['---------------------------------交易记录明细列表------------------------------------']
                // ];
                // let afterData = [
                //     ['------------------------------------------------------------------------------------']
                // ];
                let beforeData = [...this.beforeData];
                let afterData = [...this.afterData];

                beforeData = this.formatDataFillStr(beforeData, tHeader);
                afterData = this.formatDataFillStr(afterData, tHeader);

                const filename = formatStrParse(this.filename);

                excel.export_json_to_excel({
                    beforeData,
                    afterData,
                    header: tHeader,
                    data,
                    filename,
                    bookType: this.bookType
                });
                this.downloadLoading = false;
            });
        },
        formatJson(filterVal, jsonData) {
            return jsonData.map(v => filterVal.map(j => v[j]));
        },
        // 把beforeData, afterData数组补充 空字符串
        formatDataFillStr(data, tHeader) {
            const maxLength = Math.max(tHeader.length, ...data.map(item => item.length));

            return data.map(item => new Array(maxLength).fill('').map((emptyStr, index) => item[index] || emptyStr));
        }
    }
};
</script>
<style lang="scss" scoped>
.select-excel {
    display: inline-block;
}
</style>

// formatStrParse.js

/**
 * @description 字符串替换 "abc{YYYY_MM_DD}" => "abc2020_12_11"
 * @param {string} inputStr 字符串
 */
import moment from 'moment';
export default function formatStrParse(inputStr) {
    let dateStr = inputStr.match(/\{.+\}/g);
    if (Array.isArray(dateStr) && dateStr.length > 0) {
        dateStr.forEach(item => {
            const str = item.replace(/[{|}]/g, '');
            inputStr = inputStr.replace(/\{.+\}/g, moment().format(str));
        });
    }
    return inputStr || '';
}

组件使用

<ExcelJsonDownload
    :disabled="tableSuccessData.length === 0"
    :key="`${uploadKey}导入成功列表数据`"
    type="text"
    filename="导入成功列表数据{YYYYMMDD_HHmmss}"
    :tHeader="tHeader"
    :filterVal="filterVal"
    :data="tableSuccessData"
    :beforeData="beforeData"
    :afterData="afterData"
    bookType="csv"
    ><i class="el-icon-download"></i>下载导入成功列表数据</ExcelJsonDownload
>
const beforeData = [
    ['支付宝交易记录明细查询'],
    ['账号:[18230275891]'],
    ['起始日期:[2020-10-22 00:00:00]   终止日期:[2020-10-28 16:23:09]'],
    ['---------------------------------交易记录明细列表------------------------------------']
];
const afterData = [
    ['------------------------------------------------------------------------------------'],
    ['占位行,请勿删除该行1'],
    ['占位行,请勿删除该行2'],
    ['占位行,请勿删除该行3'],
    ['占位行,请勿删除该行4'],
    ['占位行,请勿删除该行5'],
    ['占位行,请勿删除该行6']
];