VUE Excel导入导出

纯前端导出Excel,后端api仅提供导出的数据

安装依赖包(导出Excel使用)

1
2
npm install -S file-saver xlsx
npm install -D script-loader

src目录下创建vendor目录,放置Blob.js和Export2Excel.js

下载地址

设置别名

build/webpack.base.conf.js中

module.exports->resolve->alias加入

'vendor': path.resolve(__dirname, '../src/vendor'),

template部分

使用的是elementui

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<template>
    <section>
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true" :model="filters">
                <el-form-item>
                    <el-input v-model="filters.key" placeholder="关键字"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" v-on:click="getData()"><i class="el-icon-search el-icon--left"></i>搜索
                    </el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleAdd">新增</el-button>
                </el-form-item>
                <el-form-item>
	                <!-- 上传 -->
                    <el-upload
                            class="upload-demo"
                            :action="uploadAction"
                            :show-file-list="false"
                            :multiple="false"
                            :limit="1"
                            :onError="uploadError"
                            :onSuccess="uploadSuccess"
                            :beforeUpload="beforeAvatarUpload">
                        <el-button type="primary" :loading="uploadLoading">上传<i class="el-icon-upload el-icon--right"></i></el-button>
                    </el-upload>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" v-on:click="handleDownload('batch')" :disabled="this.sels.length===0"
                               :loading="batchDownloadLoading">导出选中
                    </el-button>
                    <el-button type="primary" v-on:click="handleDownload('all')" :loading="allDownloadLoading">导出全部
                    </el-button>
                    <el-button type="success" v-on:click="handleDownload('base')" :loading="baseDownloadLoading">下载模板
                    </el-button>
                </el-form-item>
            </el-form>
        </el-col>
        <!--列表-->
        <el-table :data="data" highlight-current-row v-loading="listLoading" @selection-change="selsChange" border
                  style="width: 100%;">
            <el-table-column type="selection" min-width="55">
            </el-table-column>
            <el-table-column prop="company" label="公司" min-width="240" :show-overflow-tooltip="true" fixed>
            </el-table-column>
            <el-table-column prop="name_tag" label="姓名(标签)" min-width="140" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="job" label="职位" min-width="140" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="industry" label="行业" min-width="140" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="area" label="地区" min-width="120" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="telephone" label="电话" min-width="140" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="email" label="邮箱" min-width="220" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="addr" label="地址" min-width="320" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="landline" label="公司座机" min-width="140" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="remark" label="备注" min-width="320" show-overflow-tooltip>
            </el-table-column>
            <el-table-column label="操作" min-width="140" fixed="right">
                <template slot-scope="scope">
                    <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="handleDel(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--工具条-->
        <el-col :span="24" class="toolbar">
            <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
            <el-button type="primary" v-on:click="handleDownload('batch')" :disabled="this.sels.length===0"
                       :loading="batchDownloadLoading">导出选中
            </el-button>
            <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="limit"
                           :total="total" style="float:right;">
            </el-pagination>
        </el-col>
    </section>
</template>

script部分

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
<script>
    import util from '../../common/js/util'
    //import NProgress from 'nprogress'
    import {getDataListPage, removeData, batchRemoveData, editData, addData} from '../../api/api';

    export default {
        data() {
            return {
                filters: {
                    key: '',
                },
                data: [],
                total: 0,
                limit: 15,
                page: 1,
                listLoading: false,
                uploadLoading: false,
                allDownloadLoading: false,
                batchDownloadLoading: false,
                baseDownloadLoading: false,
                sels: [],//列表选中列
                uploadAction:'',
                baseUpload: [
                    {
                        company: '',
                        name: '',
                        tag: '',
                        job: '',
                        industry: '',
                        area: '',
                        telephone: '',
                        email: '',
                        addr: '',
                        landline: '',
                        remark: '',
                    }
                ],
            }
        },
        methods: {
            handleDownload(type) {
                let date = new Date();
                let fileName = 'PartADataManage-' + date.getFullYear() + '-' + date.getMonth() + '-' + date.getDay() + '-' + date.getHours() + '-' + date.getMinutes();
                let tHeader = ['公司', '姓名(标签)', '职位', '行业', '地区', '电话', '邮箱', '地址', '公司座机', '备注'];
                let filterVal = ['company', 'name_tag', 'job', 'industry', 'area', 'telephone', 'email', 'addr', 'landline', 'remark'];
                switch (type) {
                    case 'base':
                        this.baseDownloadLoading = true;
                        this.download(
                            'PartADataManage-Base',
                            ['公司', '姓名', '标签', '职位', '行业', '地区', '电话', '邮箱', '地址', '公司座机', '备注'],
                            ['company', 'name', 'tag', 'job', 'industry', 'area', 'telephone', 'email', 'addr', 'landline', 'remark'],
                            this.baseUpload
                        );
                        break;
                    case 'batch':
                        this.batchDownloadLoading = true;
                        this.download(fileName, tHeader, filterVal, this.sels);
                        break;
                    case 'all':
                        this.allDownloadLoading = true;
                        let para = {
                            key: this.filters.key,
                            page: -1
                        };
                        getDataListPage(para).then((res) => {
                            this.download(fileName, tHeader, filterVal, res.data.data);
                        });
                        break;
                }
            },
            download(fileName, tHeader, filterVal, dataList) {
                require.ensure([], () => {
                    const {
                        export_json_to_excel
                    } = require('vendor/Export2Excel');
                    const data = this.formatJson(filterVal, dataList);
                    export_json_to_excel(tHeader, data, fileName);
                });
                this.allDownloadLoading = false;
                this.batchDownloadLoading = false;
                this.baseDownloadLoading = false;
            },
            // 参数过滤
            formatJson(filterVal, jsonData) {
                console.log(jsonData);
                return jsonData.map(v => filterVal.map(j => v[j]))
            },
            // 上传成功后的回调
            uploadSuccess(res, file, fileList) {
                this.uploadLoading=false;
                this.listLoading=false;
                if (res.code === 200) {
                    this.$message({
                        message: res.message,
                        type: 'success'
                    });
                    this.getData();
                } else {
                    this.$message({
                        message: res.message ? res.message : '上传失败,服务器出错!',
                        type: 'error'
                    });
                }
            },
            // 上传错误
            uploadError(res, file, fileList) {
                this.uploadLoading=false;
                this.listLoading=false;
                this.$message({
                    message: '上传失败,服务器出错!',
                    type: 'error'
                });
            },
            // 上传前对文件的大小的判断
            beforeAvatarUpload(file) {
                this.listLoading=true;
                this.uploadLoading=true;
                const extension = file.name.split('.')[1] === 'xlsx';
                const isLt2M = file.size / 1024 / 1024 < 10;
                if (!extension) {
                    this.listLoading=false;
                    this.uploadLoading=false;
                    this.$message({
                        showClose: true,
                        message: '上传模板只能是xlsx格式!',
                        type: 'error'
                    });
                }
                if (!isLt2M) {
                    this.uploadLoading=false;
                    this.listLoading=false;
                    this.$message({
                        showClose: true,
                        message: '上传模板大小不能超过 10MB!',
                        type: 'error'
                    });
                }
                return extension && isLt2M;
            },
            setUploadAction(){
                let user = sessionStorage.getItem('user');
                this.uploadAction = 'http://api.com/data?access_token'+user.access_token;
            }
        },
        mounted() {
            this.getData();
            this.setUploadAction();
        }
    }

</script>

转载使用注明出处。原文链接 https://heimo-he.github.io/vue/2018/03/30/vue-excel/