Skip to content

Commit 21b3687

Browse files
committed
Create CSVDownloadService
1 parent 94bf797 commit 21b3687

File tree

3 files changed

+28
-1
lines changed

3 files changed

+28
-1
lines changed

src/AstroPanda.Blazor.Toolkit/AstroPanda.Blazor.Toolkit.csproj

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@
88

99
<ItemGroup>
1010
<PackageReference Include="BlazorComponentBus" Version="2.2.0" />
11-
<PackageReference Include="Blazored.LocalStorage" Version="4.5.0" />
11+
<PackageReference Include="Blazored.LocalStorage" Version="4.5.0" />
12+
<PackageReference Include="CsvHelper" Version="33.1.0" />
1213
</ItemGroup>
1314

1415
<ItemGroup Condition="'$(TargetFramework)' == 'net8.0'">
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
using System.Text;
2+
3+
namespace AstroPanda.Blazor.Toolkit.Services;
4+
5+
public class CSVDownloadService<T>(IDownloadService _downloads) : ICSVDownloadService<T>
6+
{
7+
public async Task DownloadLocalAsync(string fileName, IEnumerable<T> collection)
8+
{
9+
using var stringWriter = new StringWriter();
10+
using var csvWriter = new CsvHelper.CsvWriter(stringWriter, System.Globalization.CultureInfo.InvariantCulture, true);
11+
12+
csvWriter.WriteHeader<T>();
13+
csvWriter.NextRecord();
14+
csvWriter.WriteRecords(collection);
15+
16+
using var receivingStream = new MemoryStream(Encoding.UTF8.GetBytes(stringWriter.ToString()));
17+
18+
await _downloads.DownloadLocalAsync(fileName, receivingStream);
19+
}
20+
}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
namespace AstroPanda.Blazor.Toolkit.Services;
2+
3+
public interface ICSVDownloadService<T>
4+
{
5+
public Task DownloadLocalAsync(string fileName, IEnumerable<T> collection);
6+
}

0 commit comments

Comments
 (0)