当前我能够读取excel但无法验证,如果用户选择其他文件而不是excel文件,则需要弹出“请选择excel文件”
Component.html
<input type="file" accept=".xlsx" class="btn btn-success" (change)="onFileChange($event)">
<button type="file" class="btn dark btn-outline"
(click)="uploadfile()">Upload</button>
Component.ts
data=[];
onFileChange(evt: any) {
debugger
/* wire up file reader */
const target: DataTransfer = <DataTransfer>(evt.target);
if (target.files.length == 1 && evt.target.accept === ".xlsx" ){
const reader: FileReader = new FileReader();
reader.onload = (e: any) => {
/* read workbook */
const bstr: string = e.target.result;
const wb: XLSX.WorkBook = XLSX.read(bstr, {type: 'binary'});
console.log(wb);
/* grab first sheet */
const wsname: string = wb.SheetNames[0];
const ws: XLSX.WorkSheet = wb.Sheets[wsname];
/* save data */
this.data = <any>(XLSX.utils.sheet_to_json(ws, {header: 1}));
};
reader.readAsBinaryString(target.files[0]);
}
}
------
uploadfile() {
let keys = this.data.shift();
let resArr = this.data.map((e) => {
let obj = {};
keys.forEach((key, i) => {
obj[key] = e[i];
});
return obj;
});
console.log(resArr);
const _data = {
data: resArr
}
this.cinemaService.newoperater(_data).subscribe();
}
onFileChange()
此方法将读取数据&amp; uploadfile()
此方法会将数组数组转换为对象并将其发送到API
请帮我验证excel文件
答案 0 :(得分:1)
您可以直接将HTML元素设置为仅接受csv:
<input type="file" ID="fileSelect" accept=".xlsx, .xls, .csv"/>
HTML Input="file" Accept Attribute File Type (CSV)
修改强>
某些浏览器(即Safari 10)可能在使用<input type="file" accept=".csv" />
时遇到问题。在这种情况下使用
<input type="file" accept="text/csv" />
问候
答案 1 :(得分:0)
列表项
var reader = new FileReader();
reader.onload = (e) => {
let csvData = reader.result;
let csvRecordsArray = (<any>csvData).trim().split(/\r\n|\n/);
let header = csvRecordsArray[0].split(",");
// for (var j = 0; j <= header.length; j++) {
//if (header[j] == "") {
//this.helper.showAlertMessage("Missing Header in CSV file.", "error");
//this.myvariable.nativeElement.value = '';
let headerdata = header.length;
console.log(headerdata)
for (var i = 1; i <= csvRecordsArray.length; i++) {
var data = csvRecordsArray[i].split(",");
var dataCount = data.length;
if (headerdata !== dataCount) {
this.helper.showAlertMessage("Missing column or Invalid in CSV file.", "error");
this.myvariable.nativeElement.value = '';
}
}
//}
// }
}
reader.readAsText(event.target.files[0]);
const resp = await this.fileObjectService.uploadFile(this.fileObject.databaseId, file, this.fileObject.tableName, 10);
`