我使用KnockoutJS在我的MVC項目加載csv文件&提供了導入機制的簡單驗證時如何處理空行閱讀CSV文件中的JavaScript
的工作流程如下:
- 用戶選擇一個CSV文件(提供樣本)。
- 用戶單擊按鈕(weehoo ...)。
- 客戶端代碼採用CSV,解析並加載到KnockoutJS數組中。 所有工作完美,但我可以上傳文件,但問題是我的代碼加載在CSV文件中的空行,我不希望用戶導入文件
此之前刪除空行手冊的例子CSV行:
Account_id,External_id,Amount,Transaction_Date,Office_date,Bank,Receipt_nbr,Type,statement,receipt,
0559394,,5,6/20/2017,7/7/2017,Cash,1729002903597,PNL,172900290,3597,
0099952,,19,6/20/2017,7/7/2017,Cash,1729002903653,PNL,172900290,3653,
,,,,,,,,,,
,,,,,,,,,,
,,,,,,,,,,
這裏用我的代碼上傳文件:
$('#lnkUpload').click(function() {
var FileToRead = document.getElementById('UserFile');
if (FileToRead.files.length > 0) {
var reader = new FileReader();
// assign function to the OnLoad event of the FileReader
// non synchronous event, therefore assign to other method
reader.onload = Load_CSVData;
// call the reader to capture the file
reader.readAsText(FileToRead.files.item(0));
}
self.userModel.removeAll();
});
function Load_CSVData(e) {
self.userModel.removeAll();
CSVLines = e.target.result.split(/\r\n|\n/);
$CSVLines = CSVLines.slice(1);
$.each($CSVLines, function (i, item) {
var element = item.split(","); // builds an array from comma delimited items
var LAccount_id = (element[0] == undefined) ? "" : element[0].trim();
var LExternal_id = (element[1] == undefined) ? "" : element[1].trim();
var LAmount = (element[2] == undefined) ? "" : element[2].trim();
var LTransaction_date = (element[3] == undefined) ? "" : element[3].trim();
var LOffice_date = (element[4] == undefined) ? "" : element[4].trim();
var LBank = (element[5] == undefined) ? "" : element[5].trim();
var LReceipt_nbr = (element[6] == undefined) ? "" : element[6].trim();
var LType = (element[7] == undefined) ? "" : element[7].trim();
var Lstatement = (element[8] == undefined) ? "" : element[8].trim();
var Lreceipt = (element[9] == undefined) ? "" : element[9].trim();
self.userModel.push(new userModel()
.Account_id(LAccount_id)
.External_id(LExternal_id)
.Amount(LAmount)
.Transaction_date(LTransaction_date)
.Office_date(LOffice_date)
.Bank(LBank)
.Receipt_nbr(LReceipt_nbr)
.Type(LType)
.statement(Lstatement)
.receipt(Lreceipt))
});
}
如何更新代碼忽略和跳過空行或把他們當作輸入文件或結束其他建議
'if(item.length <= 10){...'在循環中是跳過逗號或空行的一種方法。 –