Skip to content

Instantly share code, notes, and snippets.

@DavideDunne
Created February 25, 2024 17:57
Show Gist options
  • Save DavideDunne/89eb62925250b846255ca3185e796bd9 to your computer and use it in GitHub Desktop.
Save DavideDunne/89eb62925250b846255ca3185e796bd9 to your computer and use it in GitHub Desktop.
Blazor component for exporting a list of objects to a csv
@using System.IO
@using CsvHelper
@using System.Globalization
@inject IJSRuntime JS
@code {
/// <summary>
/// Export to CSV from a Collection by clicking a button
/// Code obtained from: https://learn.microsoft.com/en-us/aspnet/core/blazor/file-downloads?view=aspnetcore-6.0#download-from-a-stream
/// https://joshclose.github.io/CsvHelper/getting-started/#writing-a-csv-file
/// </summary>
[Parameter, EditorRequired]
public IEnumerable<object>? objects { get; set; }
[Parameter, EditorRequired]
public string? FileName { get; set; }
[Parameter, EditorRequired]
public string? TextDisplay { get; set; }
private Stream GetFileStream()
{
var memoryStream = new MemoryStream();
using (var streamWriter = new StreamWriter(memoryStream, leaveOpen: true))
using (var csvWriter = new CsvWriter(streamWriter, culture: CultureInfo.InvariantCulture))
{
csvWriter.WriteRecords(objects);
}
// Reset memory stream
memoryStream.Position = 0;
return memoryStream;
}
private async Task DownloadFileFromStream()
{
using var fileStream = GetFileStream();
using var streamRef = new DotNetStreamReference(stream: fileStream);
await JS.InvokeVoidAsync("downloadFileFromStream", FileName, streamRef);
}
}
<MudIconButton Icon="@Icons.Material.Filled.Download" Color="Color.Secondary" Size="Size.Small" aria-label="Export to CSV" OnClick="DownloadFileFromStream">@TextDisplay</MudIconButton>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment