Angular 7读取Excel文件的第一列并将其保存到数组中 [英] Angular 7 reading the first column of an excel file and save it into an array

查看:327
本文介绍了Angular 7读取Excel文件的第一列并将其保存到数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试上传一个Excel文件,其中第一列是ID列.

I am trying to upload an excel file, where the first column is an ID column.

我需要获取所有ID并将其保存到数组中,以便以后将其用于数据管理.

I need to take all the IDs and save them into an array to use them later for data management.

我正在使用XLSX库:

import {read, write, utils} from 'xlsx';

对于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>

我从开始:

read()
{
    const file = new FileReader();
}

但是我无法告诉文件阅读器读取上传的文件.

But I am not able to tell the file reader to read the uploaded file.

编辑

我尝试使用文件输入的change事件:

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.

推荐答案

此答案适用于.csv文件:

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);
        };
    }
}

这篇关于Angular 7读取Excel文件的第一列并将其保存到数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆