You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何通过POST方法将Angular的Excel文件数据传递至.NET Core Web API

嘿,我刚好做过类似的Excel上传+数据同步需求,给你梳理下从Angular到Web API的完整实现步骤,分前端和后端两部分来拆解,两种主流方案任你选:

在Angular中通过POST传递Excel数据到Web API的完整方案

一、前端Angular处理流程

这里分两种常见场景:一种是前端先解析Excel为JSON数据再传递,另一种是直接上传二进制文件让后端解析。

1. 准备工作(如需前端解析Excel)

先安装SheetJS(xlsx)库来解析Excel文件:

npm install xlsx

2. 场景1:前端解析Excel为JSON后传递

组件模板(HTML)

<input type="file" accept=".xlsx, .xls" (change)="onFileSelected($event)">
<button (click)="sendParsedData()" [disabled]="!excelData.length">发送解析后的数据</button>

组件逻辑(TypeScript)

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import * as XLSX from 'xlsx';

@Component({
  selector: 'app-excel-upload',
  templateUrl: './excel-upload.component.html',
  styleUrls: ['./excel-upload.component.css']
})
export class ExcelUploadComponent {
  selectedFile: File | null = null;
  excelData: any[] = [];

  constructor(private http: HttpClient) {}

  onFileSelected(event: Event) {
    const target = event.target as HTMLInputElement;
    this.selectedFile = target.files?.[0] || null;
    
    if (this.selectedFile) {
      const reader = new FileReader();
      reader.onload = (e) => {
        const arrayBuffer = e.target?.result as ArrayBuffer;
        const workbook = XLSX.read(arrayBuffer, { type: 'array' });
        const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
        // 解析为JSON,header:1表示第一行作为表头
        this.excelData = XLSX.utils.sheet_to_json(firstSheet, { header: 1 });
      };
      reader.readAsArrayBuffer(this.selectedFile);
    }
  }

  sendParsedData() {
    if (!this.excelData.length) return;
    
    this.http.post('https://你的API地址/api/excel/upload-data', this.excelData)
      .subscribe({
        next: (res) => {
          console.log('数据发送成功!', res);
          // 这里可以添加成功提示弹窗等交互
        },
        error: (err) => {
          console.error('发送失败:', err);
          // 错误提示逻辑
        }
      });
  }
}

3. 场景2:直接上传Excel二进制文件

如果不想在前端解析,直接把文件传给后端处理,用FormData即可:

sendRawFile() {
  if (!this.selectedFile) return;
  
  const formData = new FormData();
  formData.append('excelFile', this.selectedFile, this.selectedFile.name);
  
  this.http.post('https://你的API地址/api/excel/upload-file', formData, {
    // 注意:FormData不需要手动设置Content-Type,浏览器会自动添加multipart/form-data和boundary
  }).subscribe({
    next: (res) => console.log('文件上传成功!', res),
    error: (err) => console.error('上传失败:', err)
  });
}

二、后端Web API接收处理

对应前端的两种场景,后端也有两种接收方式,这里以ASP.NET Core为例:

1. 接收JSON格式的解析后数据

[ApiController]
[Route("api/excel")]
public class ExcelController : ControllerBase
{
    [HttpPost("upload-data")]
    public IActionResult UploadParsedData([FromBody] List<List<object>> excelData)
    {
        if (excelData == null || excelData.Count <= 1) // 至少要有表头+一行数据
            return BadRequest("无效的Excel数据");

        // 提取表头和数据行
        var headers = excelData[0];
        var dataRows = excelData.Skip(1);

        // 这里写你的业务逻辑:映射为实体类、插入SQL表
        foreach (var row in dataRows)
        {
            // 示例:var entity = new YourEntity {
            //   ColumnA = row[0]?.ToString(),
            //   ColumnB = Convert.ToInt32(row[1]),
            //   ...
            // };
            // 执行SQL插入操作
        }

        return Ok(new { Message = "数据接收并处理完成" });
    }
}

2. 接收二进制Excel文件并解析

先安装EPPlus库(用于后端解析Excel):

Install-Package EPPlus

然后写控制器逻辑:

using OfficeOpenXml;

[ApiController]
[Route("api/excel")]
public class ExcelController : ControllerBase
{
    [HttpPost("upload-file")]
    public IActionResult UploadRawFile(IFormFile excelFile)
    {
        if (excelFile == null || excelFile.Length == 0)
            return BadRequest("请选择有效的Excel文件");

        // 设置EPPlus许可证(非商业使用可直接用此配置)
        ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

        using (var package = new ExcelPackage(excelFile.OpenReadStream()))
        {
            var worksheet = package.Workbook.Worksheets.First();
            int rowCount = worksheet.Dimension?.Rows ?? 0;
            int colCount = worksheet.Dimension?.Columns ?? 0;

            // 从第二行开始读取数据(假设第一行是表头)
            for (int row = 2; row <= rowCount; row++)
            {
                var column1 = worksheet.Cells[row, 1].Text;
                var column2 = int.TryParse(worksheet.Cells[row, 2].Text, out int val) ? val : 0;
                // 构建实体并插入SQL表
            }
        }

        return Ok(new { Message = "文件上传并处理完成" });
    }
}

三、关键注意事项

  • 跨域问题:如果Angular和API不在同一域名下,需在Web API中配置CORS,允许Angular的访问地址:
    builder.Services.AddCors(options =>
    {
        options.AddPolicy("AllowAngular", policy =>
        {
            policy.WithOrigins("http://localhost:4200") // 替换为你的Angular地址
                  .AllowAnyHeader()
                  .AllowAnyMethod();
        });
    });
    // 记得在中间件中启用CORS:app.UseCors("AllowAngular");
    
  • 文件大小限制:如果Excel文件较大,需调整API的请求大小限制:
    builder.Services.Configure<FormOptions>(options =>
    {
        options.MultipartBodyLengthLimit = 20 * 1024 * 1024; // 20MB,按需调整
    });
    

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

火山引擎 最新活动