问题
I am trying to upload an excel file, where the first column is an ID column.
I need to take all the IDs and save them into an array to use them later for data management.
I am using XLSX
library:
import {read, write, utils} from 'xlsx';
And for the html:
<input type="file" value="Upload Excel/CSV file" (change)="upload($event)" accept=".xlsx, .xls, .csv"/>
<button mat-fab color="warn" (click)="read()"><mat-icon color="warn">attach_file</mat-icon>Read Data</button>
I started with:
read()
{
const file = new FileReader();
}
But I am not able to tell the file reader to read the uploaded file.
EDIT
I tried to use the change event of the file input:
upload(e)
{
let input = e.target;
for (var index = 0; index < input.files.length; index++) {
let reader = new FileReader();
reader.onload = () => {
// this 'text' is the content of the file
var text = reader.result;
console.log(reader.result)
}
reader.readAsText(input.files[index]);
};
}
But the read result is like an encryption.
回答1:
This answer will work for .csv files :
<input id="file" type="file" accept=".csv" (change)="fileUpload($event.target.files)">
fileUpload(files) {
if (files && files.length > 0) {
const file: File = files.item(0);
const reader: FileReader = new FileReader();
reader.readAsText(file);
reader.onload = (e) => {
const res = reader.result as string; // This variable contains your file as text
const lines = res.split('\n'); // Splits you file into lines
const ids = [];
lines.forEach((line) => {
ids.push(line.split(',')[0]); // Get first item of line
});
console.log(ids);
};
}
}
回答2:
You should probably let the library decide how to read the workbook, instead of reading it as if it were text.
I can't test this at the moment, but it could look something like this, using an array buffer:
var reader = new FileReader();
reader.onload = function(e) {
var data = new Uint8Array(e.target.result);
var workbook = XLSX.read(data, {type:"array"});
// collect your ID's here
};
reader.readAsArrayBuffer(input.files[index]);
来源:https://stackoverflow.com/questions/55219514/angular-7-reading-the-first-column-of-an-excel-file-and-save-it-into-an-array