How to read an uploaded Excel document using SfUploader in C#?
Syncfusion Excel (XlsIO) library is a .NET Excel library used to create, read, and edit Excel documents. Also, converts Excel documents to PDF files.
This article will explore how to read an uploaded Excel document using SfUploader.
Steps for reading an uploaded Excel document using SfUploader programmatically:
Step 1: Create a new blazor web assembly application.
Step 2: Install Syncfusion.XlsIO.Net.Core , Syncfusion.Blazor.Inputs and Syncfusion.Blazor.Themes NuGet package as a reference to your blazor application from NuGet.org.
Step 3: Create a razor file named Excel under Pages folder and add the following namespaces in the file.
C#
@page "/Excel"
@using Syncfusion.XlsIO;
@using Syncfusion.Drawing;
@using Syncfusion.Blazor.Inputs
@using System.IO;
@inject Microsoft.JSInterop.IJSRuntime JS
Step 4: Add the Syncfusion Blazor service in the Program.cs file.
C#
using Syncfusion.Blazor;
// Add services to the container
builder.Services.AddSyncfusionBlazor();
Step 5: Add the theme and script references in the head section of the index.html file.
HTML
<head>
....
<link href="_content/Syncfusion.Blazor.Themes/bootstrap5.css" rel="stylesheet" />
<script src="_content/Syncfusion.Blazor.Core/scripts/syncfusion-blazor.min.js" type="text/javascript"></script>
</head>
Step 6: Include the following code snippet to add the Syncfusion Blazor file upload component in the Excel.razor file.
CSHTML
<h2>Syncfusion Excel library (Essential XlsIO)</h2>
<p>Syncfusion Excel library (Essential XlsIO) is a Blazor Excel library used to create, read, edit, and convert Excel files in your applications without Microsoft Office dependencies.</p>
<SfUploader AutoUpload="true">
<UploaderEvents ValueChange="@OnChange"></UploaderEvents>
</SfUploader>
Step 7: Include the following code snippet to show how to read a value from the uploaded Excel document using SfUploader in the Excel.razor file.
C#
@code {
private async Task OnChange(UploadChangeEventArgs args)
{
try
{
foreach (var file in args.Files)
{
var path = @"" + file.FileInfo.Name;
FileStream filestream = new FileStream(path, FileMode.Create, FileAccess.ReadWrite);
await file.File.OpenReadStream(long.MaxValue).CopyToAsync(filestream);
filestream.Position = 0;
await ReadExcel(filestream);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
// Read an Excel document
async Task ReadExcel(FileStream fileStream)
{
//Create an instance of ExcelEngine
using (ExcelEngine excelEngine = new ExcelEngine())
{
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Xlsx;
IWorkbook workbook = application.Workbooks.Open(fileStream);
IWorksheet worksheet = workbook.Worksheets[0];
//Read a cell value from the uploaded document
string value = worksheet.Range["A3"].Value;
//Save the wokrbook as a stream
using (MemoryStream stream = new MemoryStream())
{
workbook.SaveAs(stream);
//Download the Excel document in the browser
await JS.SaveAs("Output.xlsx", stream.ToArray());
}
}
}
}
Step 8: Create a class file with name as FileUtils and add the following code to invoke the JavaScript action for downloading the file in browser.
C#
public static class FileUtils
{
public static ValueTask<object> SaveAs(this IJSRuntime js, string filename, byte[] data)
=> js.InvokeAsync<object>(
"saveAsFile",
filename,
Convert.ToBase64String(data));
}
Step 9: Add the following JavaScript function in the index.html file present under wwwroot.
HTML
<script type="text/javascript">
function saveAsFile(filename, bytesBase64) {
if (navigator.msSaveBlob)
{
//Download document in Edge browser
var data = window.atob(bytesBase64);
var bytes = new Uint8Array(data.length);
for (var i = 0; i < data.length; i++)
{
bytes[i] = data.charCodeAt(i);
}
var blob = new Blob([bytes.buffer], { type: "application/octet-stream" });
navigator.msSaveBlob(blob, filename);
}
else
{
var link = document.createElement('a');
link.download = filename;
link.href = "data:application/octet-stream;base64," + bytesBase64;
document.body.appendChild(link); // Needed for Firefox
link.click();
document.body.removeChild(link);
}
}
</script>
Step 10: Add the following code in NavMenu.razor file present under Layout folder.
CSHTML
<div class="nav-item px-3">
<NavLink class="nav-link" href="Excel">
<span class="oi oi-list-rich" aria-hidden="true"></span> Excel
</NavLink>
</div>
Download a complete working sample demonstrating how to read an uploaded Excel document using SfUploader in C# from here.
See Also:
How to create, read, and edit Excel files in blazor?
Take a moment to peruse the documentation, where you can find basic worksheet data manipulation options along with features like Conditional Formatting, worksheet calculations through Formulas, adding Charts in worksheets or workbooks, organizing and analyzing data through Tables and Pivot Tables, appending multiple records to a worksheet using Template Markers, and most importantly PDF and Image conversions with code examples.
Refer here to explore the rich set of Syncfusion Excel (XlsIO) library features.
Note:
Starting with v16.2.0.x, if you reference Syncfusion assemblies from the trial setup or the NuGet feed, include a license key in your projects. Refer to the link to learn about generating and registering the Syncfusion license key in your application to use the components without a trial message.