问题
I want to read excel file using angular code. my file is stored somewhere in my local system e.g, C:/data/test.xlsx
I have already tried loading with readFile() & load() methods of exceljs.
they fail to read anything, instead they give error
回答1:
I found the way to read excel file from Angular code. Convert the file into ArrayBuffer and read it using exceljs
- Importing Exceljs in angular service/component
import * as Excel from 'exceljs/dist/exceljs.min.js';
- Modify tsconfig.app.json
compilerOptions: {
paths": {
"exceljs": [
"node_modules/exceljs/dist/exceljs.min"
]
}
}
- Open file from html code.
<input id="uploadBtn" type="file" (change)="readExcel($event)"
class="upload input-common" required />
- Using exceljs for reading file.
readExcel(event) {
const workbook = new Excel.Workbook();
const target: DataTransfer = <DataTransfer>(event.target);
if (target.files.length !== 1) {
throw new Error('Cannot use multiple files');
}
/**
* Final Solution For Importing the Excel FILE
*/
const arryBuffer = new Response(target.files[0]).arrayBuffer();
arryBuffer.then(function (data) {
workbook.xlsx.load(data)
.then(function () {
// play with workbook and worksheet now
console.log(workbook);
const worksheet = workbook.getWorksheet(1);
console.log('rowCount: ', worksheet.rowCount);
worksheet.eachRow(function (row, rowNumber) {
console.log('Row: ' + rowNumber + ' Value: ' + row.values);
});
});
});
}
来源:https://stackoverflow.com/questions/56595103/how-to-import-excel-file-in-angular-using-exceljs