将jsx中的csv文件读取到const数组

时间:2020-06-17 13:35:09

标签: javascript reactjs csv jsx

我正在尝试将本地csv文件读取到jsx中的const数组。这是我的jsx文件:

const thArray = ["ID", "Name", "Salary", "Country", "City"];
const tdArray = [
];


module.exports = {
    thArray,
    tdArray
  };

我的本​​地csv文件(Roster.csv)具有以下数据:

ID, Name, Salary, Country, City
1, Dakota Rice, $36,738, Niger, Oud-Turnhout
2, Minerva Hooper, $23,789, Curaçao, Sinaai-Waas

有没有一个库可以让我像这样从csv中填充数据到tdArray:

const tdArray = [
  ["1", "Dakota Rice", "$36,738", "Niger", "Oud-Turnhout"],
  ["2", "Minerva Hooper", "$23,789", "Curaçao", "Sinaai-Waas"]
];

1 个答案:

答案 0 :(得分:0)

您可以为此目的使用库 papaparse https://www.papaparse.com

看这个例子对你可能是有希望的:

 constructor(props) {
        super(props);

        this.state = {
            data: []
        };

        this.getData = this.getData.bind(this);
    }

    componentWillMount() {
        this.getCsvData();
    }

    fetchCsv() {
        return fetch('/data/data.csv').then(function (response) {
            let reader = response.body.getReader();
            let decoder = new TextDecoder('utf-8');

            return reader.read().then(function (result) {
                return decoder.decode(result.value);
            });
        });
    }

    getData(result) {
        this.setState({data: result.data});
    }

    async getCsvData() {
        let csvData = await this.fetchCsv();

        Papa.parse(csvData, {
            complete: this.getData
        });
    }
相关问题