-
Notifications
You must be signed in to change notification settings - Fork 0
CSV Download
We want to get event table of database in CSV format, for this we are using CSVHelper library. CSVHelper is a library for reading and writing CSV files. It is extremely fast, flexible, and easy to use. Supports reading and writing of custom class objects.
We need to install CsvHelper package from NuGet Package Manager.
Create an interface named ICsvExporter at location Core/ProjectName.Application/Contracts/Infrastructure as below,
public interface ICsvExporter
{
byte[] ExportEventsToCsv(List<EventExportDto> eventExportDtos);
}
Create a service class named CsvExporter at location Core/Infrastructure/ProjectName.Infrastructure/FileExport to implement ICsvExporter interface,
public class CsvExporter : ICsvExporter
{
public byte[] ExportEventsToCsv(List<EventExportDto> eventExportDtos)
{
using var memoryStream = new MemoryStream();
using (var streamWriter = new StreamWriter(memoryStream))
{
using var csvWriter = new CsvWriter(streamWriter);
csvWriter.WriteRecords(eventExportDtos);
}
return memoryStream.ToArray();
}
}
Configure this in InfrastructureServiceRegistration at same location as below,
public static class InfrastructureServiceRegistration
{
public static IServiceCollection AddInfrastructureServices(this IServiceCollection services, IConfiguration configuration)
{
services.AddTransient<ICsvExporter, CsvExporter>();
return services;
}
}
Then, create a event handler named CreateEventCommandHandler at location Core/ProjectName.Application/Features/Events/Queries/GetEventsExport,
public class GetEventsExportQueryHandler : IRequestHandler<GetEventsExportQuery, EventExportFileVm>
{
private readonly IAsyncRepository<Event> _eventRepository;
private readonly IMapper _mapper;
private readonly ICsvExporter _csvExporter;
public GetEventsExportQueryHandler(IMapper mapper, IAsyncRepository<Event> eventRepository, ICsvExporter csvExporter)
{
_mapper = mapper;
_eventRepository = eventRepository;
_csvExporter = csvExporter;
}
public async Task<EventExportFileVm> Handle(GetEventsExportQuery request, CancellationToken cancellationToken)
{
var allEvents = _mapper.Map<List<EventExportDto>>((await _eventRepository.ListAllAsync()).OrderBy(x => x.Date));
var fileData = _csvExporter.ExportEventsToCsv(allEvents);
var eventExportFileDto = new EventExportFileVm() { ContentType = "text/csv", Data = fileData, EventExportFileName = $"{Guid.NewGuid()}.csv" };
return eventExportFileDto;
}
}
Demo video to get the clear result view of above implemented module.