当前位置: 首页 > 工具软件 > PapaParse > 使用案例 >

vue导入导出csv文件(插件papaparse + jschardet)

慕容成和
2023-12-01

csv的导入导出之前我写过一篇文章:https://blog.csdn.net/canlynetsky/article/details/125278779,按那篇文章导出的是带BOM头的csv文件,但是在WPS编辑后会变成GBK编码,所以依靠BOM头判断如何解析。
此文则使用vue的插件papaparse + jschardet来实现导出导入以及字符集编码的监测。
直接上代码:

<template>
    <div class="hello">
        <button @click="exportCsv">导出</button>
        <input type="file" id="files" ref="file" v-on:change="importCsv" />
        <table align="center">
            <tr>
                <th width="100">姓名</th>
                <th>年龄</th>
            </tr>
            <tr v-for="(item, i) in data" :key="i">
                <td>{{ item.name }}</td>
                <td>{{ item.age }}</td>
            </tr>
        </table>
    </div>
</template>

<script>
/* eslint-disable */

import Papa from 'papaparse'
import jschardet from 'jschardet'

export default {
    name: 'HelloWorld',
    data() {
        return {
            data: [
                { name: '张三', age: 32 },
                { name: '李四', age: 24 },
            ],
        }
    },
    methods: {
        exportCsv() {
            const header = { 'name': '姓名', 'age': '年龄' };
            export_csv(header, this.data);

            function export_csv(header, data) {
                let list = [];
                for (let i in data) {
                    let item = data[i];
                    let obj = {};
                    for (let key in header) {
                        let title = header[key];
                        let value = item[key];
                        obj[title] = value;
                    }
                    list.push(obj);
                }

                var csv = Papa.unparse(list);
                //定义文件内容,类型必须为Blob 否则createObjectURL会报错
                let content = new Blob(['\uFEFF' + csv]);
                //生成url对象
                let urlObject = window.URL || window.webkitURL || window;
                let url = urlObject.createObjectURL(content);
                //生成<a></a>DOM元素
                let el = document.createElement("a");
                //链接赋值
                el.href = url;
                el.download = "文件导出.csv";
                //必须点击否则不会下载
                el.click();
                //移除链接释放资源
                urlObject.revokeObjectURL(url);
            }
        },
        importCsv() {
            const header = { '姓名': 'name', '年龄': 'age' };
            let file = this.$refs.file.files[0];
            read_csv_file(header, file, (data) => {
                this.data = data;
                this.$refs.file.value = '';
            });
            // 检查编码,引用了 jschardet
            function check_encoding(file, callback) {
                let fReader = new FileReader();
                fReader.readAsDataURL(file);
                fReader.onload = evt => {
                    let base64_str = evt.target.result;
                    let str = atob(base64_str.split(";base64,")[1]);
                    let encoding = jschardet.detect(str).encoding;
                    if (encoding == "windows-1252") {
                        // 有时会识别错误(如UTF8的中文二字)
                        encoding = "ANSI";
                    }
                    callback(encoding);
                };
            }
            function read_csv_file(header, file, callback) {
                if (!file) {
                    return;
                }
                check_encoding(file, (encoding) => {
                    Papa.parse(file, {
                        encoding,
                        complete: res => {
                            // UTF8 \r\n与\n混用时有可能会出问题
                            let data = res.data;
                            let col = 0;
                            let titles = {};
                            for (let i in data[0]) {
                                let key = data[0][i];
                                titles[col++] = header[key] ? header[key] : key;
                            }
                            let list = [];
                            for (let i = 1; i < data.length; i++) {
                                let arr = data[i];
                                if (arr.length == 1 && arr[0] == '') {
                                    continue;
                                }
                                let obj = {};
                                for (let j in arr) {
                                    obj[titles[j]] = arr[j];
                                }
                                list.push(obj);
                            }
                            callback(list)
                        }
                    });
                });
            }
        },
    }
}
</script>

项目中需要安装这两个插件:npm install papaparse jschardet -S

 类似资料: