How to Read Excel Sheets in ASP.NET Core C# from Angular | Step-by-Step

watch_later 7/14/2024

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.

How to Read Excel Sheets in ASP.NET Core C# from Angular

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<IActionResultUploadExcel(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 <= rowCountrow++)
                    {
                        for (int col = 1; col <= colCountcol++)
                        {
                            data.Add(worksheet.Cells[rowcol].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 httpHttpClient) { }
 
    uploadFile(fileFile): Observable<any> {
        const formDataFormData = new FormData();
        formData.append('file'filefile.name);
 
        return this.http.post(this.apiUrlformData);
    }
}

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 {
 
    selectedFileFile | null = null;
 
    constructor(private excelUploadServiceExcelUploadService) { }
 
    onFileSelected(eventany): 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.

Codingvila provides articles and blogs on web and software development for beginners as well as free Academic projects for final year students in Asp.Net, MVC, C#, Vb.Net, SQL Server, Angular Js, Android, PHP, Java, Python, Desktop Software Application and etc.

Thank you for your valuable time, to read this article, If you like this article, please share this article and post your valuable comments.

Once, you post your comment, we will review your posted comment and publish it. It may take a time around 24 business working hours.

Sometimes I not able to give detailed level explanation for your questions or comments, if you want detailed explanation, your can mansion your contact email id along with your question or you can do select given checkbox "Notify me" the time of write comment. So we can drop mail to you.

If you have any questions regarding this article/blog you can contact us on info.codingvila@gmail.com

sentiment_satisfied Emoticon