You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 2读取Excel文件:ng2-File-upload及原生JS/TS实现方法咨询

Handling Excel Files with ng2-file-upload and Native JS/TS

Great question! First off: ng2-file-upload itself doesn’t handle Excel parsing—it’s built to simplify file selection and upload workflows in Angular. But you can absolutely pair it with an Excel parsing library like SheetJS (xlsx) to read all rows and get the total row count. Here’s how to do it step by step:

Using ng2-file-upload + SheetJS in Angular (TypeScript)

1. Install Required Packages

First, install both libraries via npm:

npm install ng2-file-upload xlsx

2. Configure ng2-file-upload in Your Component

Set up the file uploader to accept Excel files only, and listen for file selection to trigger parsing:

import { Component } from '@angular/core';
import { FileUploader } from 'ng2-file-upload';
import * as XLSX from 'xlsx';

@Component({
  selector: 'app-excel-reader',
  template: `
    <input type="file" ng2FileSelect [uploader]="uploader" accept=".xlsx,.xls">
  `
})
export class ExcelReaderComponent {
  uploader: FileUploader = new FileUploader({ url: '#' }); // No actual upload URL needed for parsing

  constructor() {
    this.uploader.onAfterAddingFile = (fileItem) => {
      this.parseExcelFile(fileItem._file);
    };
  }

  private parseExcelFile(file: File): void {
    const reader = new FileReader();
    
    reader.onload = (e) => {
      const data = new Uint8Array(e.target.result as ArrayBuffer);
      const workbook = XLSX.read(data, { type: 'array' });
      
      // Grab the first worksheet (adjust if you need a specific sheet by name)
      const firstSheetName = workbook.SheetNames[0];
      const worksheet = workbook.Sheets[firstSheetName];
      
      // Convert worksheet to a JSON array (each object = 1 row, keys from headers)
      const rows = XLSX.utils.sheet_to_json(worksheet);
      
      // Get total row count (includes header row if your Excel has one)
      const totalRows = rows.length;
      
      console.log('All parsed rows:', rows);
      console.log('Total row count:', totalRows);
      
      // Use the rows data for your app logic here
    };
    
    reader.readAsArrayBuffer(file);
  }
}

Key Notes:

  • The accept=".xlsx,.xls" attribute restricts file selection to Excel formats.
  • sheet_to_json converts rows to objects with header values as keys. If your sheet has no headers, use { header: 1 } to get an array of arrays instead.

Native JavaScript/TypeScript Approach (No ng2-file-upload)

If you don’t need ng2-file-upload’s upload features and just want to parse Excel files directly, here’s a vanilla solution:

// HTML
<input type="file" id="excelFileInput" accept=".xlsx,.xls">

// TypeScript/JavaScript
document.getElementById('excelFileInput').addEventListener('change', (e) => {
  const file = (e.target as HTMLInputElement).files[0];
  if (!file) return;

  const reader = new FileReader();
  
  reader.onload = (event) => {
    const data = new Uint8Array(event.target.result as ArrayBuffer);
    const workbook = XLSX.read(data, { type: 'array' });
    
    const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
    const rows = XLSX.utils.sheet_to_json(firstSheet);
    const totalRows = rows.length;
    
    console.log('Parsed rows:', rows);
    console.log('Total rows:', totalRows);
  };
  
  reader.readAsArrayBuffer(file);
});

Additional Tips

  • For older .xls files (Excel 97-2003), SheetJS handles them seamlessly—just keep the file extension in the accept attribute.
  • If you need to exclude a header row from the count, subtract 1 from totalRows (only if your sheet has a header).
  • SheetJS has tons of customization options (skip empty rows, custom header mappings, etc.)—explore their docs for more use cases.

内容的提问来源于stack exchange,提问作者Asad Shah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:18:21