ASP.NET CoreアプリケーションでMagicodes.IEを使用してExcelファイルをエクスポートする際の基本的な実装手順を以下に示します。
必要なNuGetパッケージをインストールし、名前空間を参照します。
using Magicodes.ExporterAndImporter.Excel.AspNetCore;
Excelエクスポートの実装例を以下に示します。
[ApiController]
[Route("api/[controller]")]
public class ExcelExportController : ControllerBase
{
[HttpGet("export-by-bytes")]
public async Task<ActionResult> ExportByBytes()
{
var sampleData = GenerateSampleData(100);
var exporter = new ExcelDataGenerator();
var byteData = await exporter.GenerateExcelBytes(sampleData);
return new ExcelExportResult(byteData);
}
[HttpGet("export-by-stream")]
public async Task<ActionResult> ExportByStream()
{
var sampleData = GenerateSampleData(100);
var exporter = new ExcelDataGenerator();
var byteData = await exporter.GenerateExcelBytes(sampleData);
var stream = new MemoryStream(byteData);
return new ExcelExportResult(stream, "sample_data.xlsx");
}
[HttpGet("export-by-list")]
public async Task<ActionResult> ExportByList()
{
var dataList = GenerateSampleData(100);
return new ExcelExportResult(dataList);
}
private List<SampleModel> GenerateSampleData(int count)
{
var data = new List<SampleModel>();
for (int i = 0; i < count; i++)
{
data.Add(new SampleModel { Id = i + 1, Name = $"Sample{i}", Value = i * 100 });
}
return data;
}
}
カスタムActionResultの実装は以下の通りです。
public class ExcelExportResult<T> : ExcelExportBase where T : class, new()
{
public ExcelExportResult(IEnumerable<T> dataSource, string fileName = null)
{
DownloadName = fileName;
Data = dataSource;
}
public string DownloadName { get; }
public IEnumerable<T> Data { get; }
public async override Task ExecuteResultAsync(ActionContext httpContext)
{
var generator = new ExcelDataGenerator();
var byteData = await generator.GenerateBytes(Data);
var memoryStream = new MemoryStream(byteData);
await SaveExcelFile(httpContext, memoryStream, DownloadName);
}
}
public class ExcelExportResult : ExcelExportBase
{
public ExcelExportResult(Stream stream, string fileName = null)
{
OutputStream = stream;
DownloadName = fileName;
}
public ExcelExportResult(byte[] bytes, string fileName = null)
{
OutputStream = new MemoryStream(bytes);
DownloadName = fileName;
}
public Stream OutputStream { get; }
public string DownloadName { get; }
public async override Task ExecuteResultAsync(ActionContext httpContext)
{
await SaveExcelFile(httpContext, OutputStream, DownloadName);
}
}
public class ExcelExportBase : ActionResult
{
protected virtual async Task SaveExcelFile(ActionContext context, Stream stream, string fileName)
{
var response = context.HttpContext.Response;
response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
if (string.IsNullOrEmpty(fileName))
{
fileName = Guid.NewGuid().ToString("N") + ".xlsx";
}
else if (!fileName.EndsWith(".xlsx", StringComparison.OrdinalIgnoreCase))
{
fileName += ".xlsx";
}
response.Headers["Content-Disposition"] = $"attachment; filename={Uri.EscapeDataString(fileName)}";
await stream.CopyToAsync(response.Body);
}
}