基於前端框架react或者vue或者其他其他框架到出資料生成csv檔案,以及匯入csv檔案讀取資料的簡單例子
阿新 • • 發佈:2018-11-12
1.用npm在專案中安裝以下外掛:
npm install file-saver --save
npm install papaparse --save
npm install jschardet --save
npm install iconv-lite --save
npm install encoding --save
2.在你要編寫專案的檔案中匯入這些外掛:
import FileSaver from 'file-saver' import Papa from "papaparse" import jschardet from "jschardet" import iconv from "iconv-lite" import encoding from "encoding"
3.寫一個方法邏輯將資料生成csv檔案:
//點選批量匯出資料生成csv檔案 exportList(){ //拿到所有的資料 let data=[ { name:"小明", pwd:123, school:"未知小學", age:10 }, { name:"小紅", pwd:132, school:"未知中學", age:15 }, { name:"大紅", pwd:321, school:"未知大學", age:20 }, ]; //定義資料拼接 //str:table的每一列的標題,即為匯出後的csv檔案的每一列的標題 let str=''; str += 'name' + ',' + 'pwd' + ',' + 'school' + ',' + 'age'; //通過迴圈拿出data資料來源裡的資料,並塞到str中 for (const i in data) { //如果是第一行,不換行 str += '\n' + data[i].name + ',' + data[i].pwd + ',' + data[i].school + ',' + data[i].age } //Excel開啟後中文亂碼新增如下字串解決 let exportContent = "\uFEFF"; let blob = new Blob([exportContent + str], { type: "text/plain;charset=utf-8" }); //根據資料生成生成檔案 FileSaver.saveAs(blob, "demo.csv"); }
4.寫一個方法將csv檔案匯入生成資料讀取:
importData(e){ const file = e.target.files[0]; if (file) { let allResults=[]; const reader = new FileReader(); reader.readAsBinaryString(file); reader.onload = event => { let buf = event.target.result; const encodeType = jschardet.detect(buf).encoding; if (encodeType !== "UTF-8") { buf = encoding.convert(buf, "utf8", encodeType); } iconv.skipDecodeWarning = true; const text = iconv.decode(buf, "utf8"); Papa.parse(text, { encoding: "UTF-8", complete: results => { for(let y=0;y<results.data.length;y++){ // es6合併陣列的語法 allResults=[...allResults,results.data[y]] } //列印拿到的最終資料 console.log(allResults) } } ) } } }
5.寫一個html的標籤,基於react的繫結事件,繫結資料csv檔案匯入,accpet設定只選擇csv檔案:
<input type="file" accept=".csv" onChange={this.importData.bind(this)} />