1.在本地新建一个.csv文件
2.实现代码
安装papaparse
和jschardet
插件,npm install papapars
、npm install jschardet
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
| import React from 'react'; import { Upload, Button, Icon } from 'antd'; import Papa from 'papaparse'; import jschardet from 'jschardet';
export default class Csv extends React.Component { constructor(props) { super(props); this.state = { csvParseData: [], }; } checkEncoding = (base64Str) => { const str = atob(base64Str.split(";base64,")[1]); let encoding = jschardet.detect(str); encoding = encoding.encoding; if(encoding == "windows-1252"){ encoding = "ANSI"; } return encoding; } render() { const _this = this; const props = { beforeUpload: file => { const fReader = new FileReader(); fReader.readAsDataURL(file); fReader.onload = function(evt){ const data = evt.target.result; const encoding = _this.checkEncoding(data); Papa.parse(file, { encoding: encoding, complete: function(results) { const res = results.data; if(res[res.length - 1] === ""){ res.pop(); } _this.setState(res); console.log(res) } }); } return false; }, }; return ( <Upload {...props}> <Button> <Icon type="upload" /> 点击上传csv </Button> </Upload> ); } }
|
3.获取结果
如上图就是最终拿到的值 和我们新建测试的csv文件数据是一致的 中文也没有出现乱码 前端解析csv也就实现了