Reading Excel sheets in ASP.NET Core C# is one of the very common requirements, particularly in data import-related web applications, is to read Excel files. In this tutorial, the process from importing an Excel file from the Angular front-end to an ASP.NET Core Web API and reading its content row by row will be demonstrated. we will also learn how to upload an Excel file from Angular using formData to a Web API Core 6 Endpoint.
Prerequisites
To follow through on this tutorial, you need:
- Basic knowledge of ASP.NET Core and Angular.
- .NET 6 SDK installed.
- Angular CLI installed.
- An IDE like Visual Studio, VS Code, etc.
Step 1: Create an ASP.NET Core Web API
Create a new ASP.NET Core Web API project.
dotnet new webapi - n ExcelImportApi cd ExcelImportApi
Install NuGet packages that will be connected with reading Excel files. In this case, we'll use the very nice EPPlus library, which is dedicated to Excel files processing in .NET.
dotnet add package EPPlus
Step 2: Implement API Endpoint
Now, add a new controller named ExcelController.
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using OfficeOpenXml; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; namespace ExcelImportApi.Controllers { [Route("api/[controller]")] [ApiController] public class ExcelController : ControllerBase { [HttpPost("upload")] public async Task<IActionResult> UploadExcel(IFormFile file) { if (file == null || file.Length == 0) return BadRequest("Upload a valid Excel file."); var data = new List<string>(); using (var stream = new MemoryStream()) { await file.CopyToAsync(stream); using (var package = new ExcelPackage(stream)) { var worksheet = package.Workbook.Worksheets[0]; var rowCount = worksheet.Dimension.Rows; var colCount = worksheet.Dimension.Columns; for (int row = 1; row <= rowCount; row++) { for (int col = 1; col <= colCount; col++) { data.Add(worksheet.Cells[row, col].Text); } } } } return Ok(data); } } }
Step 3: Configure the Angular Front-End
Make a new Angular application. Then, setup a service to facilitate file upload.
ng new excel - upload - app cd excel - upload - app ng generate service excel - upload
In excel-upload.service.ts, implement the file upload functionality.
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class ExcelUploadService { private apiUrl = 'https://localhost:5001/api/excel/upload'; constructor(private http: HttpClient) { } uploadFile(file: File): Observable<any> { const formData: FormData = new FormData(); formData.append('file', file, file.name); return this.http.post(this.apiUrl, formData); } }
Component to select and upload Excel file.
ng generate component upload
On excel-upload.component.html, create an input file and button which triggers the upload process.
<input type="file"(change) = "onFileSelected($event)" /> <button (click)="onUpload()" > Upload < /button>
On excel-upload.component.ts, implement the logic for selecting and uploading a file.
import { Component } from '@angular/core'; import { ExcelUploadService } from '../excel-upload.service'; @Component({ selector: 'app-upload', templateUrl: './upload.component.html', styleUrls: ['./upload.component.css'] }) export class UploadComponent { selectedFile: File | null = null; constructor(private excelUploadService: ExcelUploadService) { } onFileSelected(event: any): void { this.selectedFile = event.target.files[0]; } onUpload(): void { if (this.selectedFile) { this.excelUploadService.uploadFile(this.selectedFile) .subscribe(response => { console.log('Upload success', response); }, error => { console.error('Upload error', error); }); } } }
Step 4: Run and Test the Application
Run the ASP.NET Core Web API and Angular application. Use the Angular front-end to select an Excel file and upload it. The API will read and return the content of this file.
Conclusion
In this tutorial, we demonstrated how to import an Excel file using formData from Angular into an ASP.NET Core Web API and read every line or cell for that matter with EPPlus, something that could prove very useful during an application procedure in need of information processing and data analysis from Excel sheets.