Angular JS解析Excel
Angular JS解析Excel
https://www.aspsnippets.com/Articles/Read-Excel-File-using-AngularJS-and-HTML5-File-API.aspx
https://www.cnblogs.com/liuxianan/p/js-excel.html
<input type="file" class="uploadButton" id="uploadZjUserFile"/>
<input type="button" class="submitButton" value="导入" ng-click="uploadFile(3)"/>
const excelSuffix = ['xlsx', 'xls'];
// 上传文件
$scope.uploadFile = function (fieldType) {
let file;
if (fieldType === 1) {
file = document.getElementById("uploadGroupFile").files[0];
$scope.uploadFileWay = true;
} else if (fieldType === 2) {
file = document.getElementById("uploadZxUserFile").files[0];
}
if (file == null) {
new hullabaloo().send("导入失败", "请选择文件", "danger");
}
if (excelSuffix.includes(file.name.substring(file.name.lastIndexOf('.') + 1).toLowerCase())) {
if (typeof (FileReader) != "undefined") {
const reader = new FileReader();
// For Browsers other than IE.
if (reader.readAsBinaryString) {
reader.onload = function (e) {
$scope.processExcel(e.target.result, fieldType);
};
reader.readAsBinaryString(file);
} else {
// For IE Browser.
reader.onload = function (e) {
let data = "";
const bytes = new Uint8Array(e.target.result);
for (let i = 0; i < bytes.byteLength; i++) {
data += String.fromCharCode(bytes[i]);
}
$scope.processExcel(data, fieldType);
};
reader.readAsArrayBuffer(file);
}
} else {
$scope.clearFileUpload();
new hullabaloo().send("导入失败", "当前浏览器不支持H5.", "danger");
}
} else {
$scope.clearFileUpload();
new hullabaloo().send("导入失败", "请上传Excel文件", "danger");
}
};
// Excel解析
$scope.processExcel = function (data, fieldType) {
// Read the Excel File data.
const workbook = XLSX.read(data, {
type: 'binary'
});
// Fetch the name of First Sheet.
const firstSheet = workbook.SheetNames[0];
// Read all rows from First Sheet into an JSON array.
const excelRows = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[firstSheet]);
// Display the data from Excel file in Table.
$scope.$apply(function () {
const result = $scope.parseRow(excelRows, fieldType);
if (result.includes(undefined)) {
$scope.clearFileUpload();
new hullabaloo().send("导入失败", "导入数据有误,请对照示例检查", "danger");
return;
}
if (fieldType === 1) {
// 组别
$scope.seargropname2 = result;
} else if (fieldType === 2) {
// 坐席
$scope.searchZxUser = result;
}
});
};
// 获取数据
$scope.parseRow = function (rows, fieldType) {
const result = [];
for (let i = 0; i < rows.length; i++) {
if (fieldType === 1) {
// column name in first row
result.push(rows[i].组别);
} else if (fieldType === 2) {
result.push(rows[i].坐席);
}
}
return result;
};
// 清空
$scope.clearFileUpload = function() {
document.getElementById("uploadGroupFile").value = '';
document.getElementById("uploadZxUserFile").value = '';
};