我在我的MVc项目中使用KnockoutJS来加载csv文件&为导入机制提供简单的验证
工作流程如下:
这是csv Lines的一个例子:
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))
});
}
如何将代码更新为忽略并跳过空行或将它们视为输入文件的结尾或任何其他建议
答案 0 :(得分:4)
您可以检测当前行是否为换行符。
if(item == "\n") { continue; }
编辑:
正如matt指出的那样,如果空格由空格组成,则上述解决方案将无效。只需擦除任何空格即可检测行是否由空格组成。
if(item == "\n" || item.trim().length == 0) { continue; }
答案 1 :(得分:0)
这将检测仅由逗号和/或空格组成的行(因此将匹配“ \ n”,“”,“,”,“,”,“,”,“等”,但不匹配“ 、、、、 1 、、、、”
if (item.match(/^[,\s]*$/)) { continue; }