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

如何在Angular页面中预览导入的多工作表Excel文件?

实现Angular中读取Excel所有工作表并切换查看

核心思路

目前你的代码仅读取了第一个工作表(wb.SheetNames[0]),要实现查看所有工作表,需要:

  • 存储所有工作表的名称和对应数据
  • 添加切换控件,让用户选择要查看的工作表
  • 根据选中的工作表渲染对应数据

修改后的组件代码(TS)

import { Component, OnInit } from '@angular/core';
import * as XLSX from 'xlsx'; 

@Component({
  selector: 'app-xlsheet',
  templateUrl: './xlsheet.component.html',
  styleUrls: ['./xlsheet.component.css']
})
export class XlsheetComponent implements OnInit{
  ngOnInit(): void {}

  // 存储所有工作表的名称和对应数据
  worksheets: {name: string, data: [][]}[] = [];
  // 当前选中的工作表索引
  currentSheetIndex = 0;

  onFileChange(evt: any){
    const target : DataTransfer = <DataTransfer>(evt.target);
    if (target.files.length !==1) throw new Error ('不能选择多个文件');   
    const reader: FileReader = new FileReader();
    reader.readAsBinaryString(target.files[0]);
    reader.onload = (e: any) => {
      const bstr: string = e.target.result;
      const wb: XLSX.WorkBook = XLSX.read(bstr, {type: 'binary'});
      
      // 遍历所有工作表,读取每个表的数据
      this.worksheets = wb.SheetNames.map(sheetName => {
        const ws: XLSX.WorkSheet = wb.Sheets[sheetName];
        return {
          name: sheetName,
          data: XLSX.utils.sheet_to_json(ws, {header:1})
        };
      });
      // 默认选中第一个工作表
      this.currentSheetIndex = 0;
    };
  } 
}

修改后的模板代码(HTML)

<div class="container">
    <h2 class="header">Excel File Utility App</h2>
    <div class="choose-file">
        <input type="file" (change)="onFileChange($event)" multiple="false"> 
        <!-- 添加工作表选择下拉框 -->
        <select *ngIf="worksheets.length > 0" [(ngModel)]="currentSheetIndex">
            <option *ngFor="let sheet of worksheets; let i = index" [value]="i">
                {{sheet.name}}
            </option>
        </select>
        <h2>Excel file content displayed below:</h2>
    </div>
    <div class="content-area" *ngIf="worksheets.length > 0">
        <table>
            <tbody>
                <tr *ngFor="let row of worksheets[currentSheetIndex].data">
                    <td *ngFor="let cell of row">
                        {{cell}}
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

关键修改说明

  • 将单个data数组替换为worksheets数组,每个元素保存工作表名称和对应数据,实现全表内容存储
  • 遍历wb.SheetNames数组,用map方法批量处理所有工作表数据
  • 前端新增下拉选择框,绑定currentSheetIndex,切换时自动更新显示的工作表内容
  • 添加*ngIf判断,避免未读取文件时渲染空内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 02:38:09