Created
August 12, 2014 06:17
-
-
Save shuxiang/84a542bdb3c096ab88d5 to your computer and use it in GitHub Desktop.
handle xlsx xls csv file in frontend js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/************************ need js lib *********************************** | |
// https://raw.githubusercontent.com/SheetJS/js-xlsx/master/dist/xlsx.core.min.js | |
// https://raw.githubusercontent.com/SheetJS/js-xls/master/dist/xls.core.min.js | |
// https://raw.githubusercontent.com/gkindel/CSV-JS/master/csv.js | |
************************************************************************/ | |
//upload file | |
function handleKVFile(e) { | |
var files = e.target.files; | |
var i,f; | |
for (i = 0, f = files[i]; i != files.length; ++i) { | |
var reader = new FileReader(); | |
var name = f.name; | |
var csv; | |
reader.onload = function(e) { | |
var data = e.target.result; | |
if (name.indexOf('.csv') > -1){ | |
csv = data; | |
}else if(name.indexOf('.xlsx') > -1){ | |
var workbook = XLSX.read(data, {type: 'binary'}); | |
csv = XLSX.utils.sheet_to_csv(workbook.Sheets[workbook.SheetNames[0]]); | |
}else if(name.indexOf('.xls') > -1 && name.indexOf('.xlsx')==-1){ | |
var workbook = XLS.read(data, {type: 'binary'}); | |
csv = XLS.utils.sheet_to_csv(workbook.Sheets[workbook.SheetNames[0]]); | |
} | |
// [[row]...] | |
var rows = CSV.parse(csv); | |
// 处理数据 | |
handleKVCsv(rows); | |
}; | |
if (name.indexOf('.csv') > -1){ | |
// xlsx导出的CSV 文件一般是GBK编码 | |
reader.readAsText(f, 'GB18030'); | |
}else{ | |
reader.readAsBinaryString(f); | |
} | |
} | |
} | |
function handleKVCsv(rows){ | |
//do some thing here | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment