Magicodes.IEを使ったASP.NET CoreでのExcelエクスポート

はじめに

ASP.NET CoreアプリケーションからExcelファイルをエクスポートするための、簡単で即用可能な方法を提供するために、Magicodes.IEライブラリはExcelエクスポート機能を独立してパッケージ化しています。これにより、開発者はライブラリをより簡単に利用し、すぐに使用を開始できます。

注意:Magicodes.IEはフレームワークの使いやすさと体験を重視してExcelエクスポートをパッケージ化していますが、使用前にその原理を理解することをお勧めします。

1. パッケージのインストール

Install-Package Magicodes.IE.Excel.AspNetCore

2. 名前空間のインポート

using Magicodes.ExporterAndImporter.Excel.AspNetCore;

3. ExcelFileResultを直接使用する

以下に示すコントローラーの例を参照してください。

[ApiController]
[Route("api/[controller]")]
public class ExcelExportController : ControllerBase
{
    /// <summary>
    /// バイト配列を使用してExcelファイルをエクスポートする
    /// </summary>
    /// <returns></returns>
    [HttpGet("ExportByByteArray")]
    public async Task<ActionResult> ExportByByteArray()
    {
        // サンプルデータを100件生成
        var dataList = GenerateSampleData(100);
        var excelExporter = new ExcelExporter();
        var excelDataBytes = await excelExporter.ExportAsByteArray<ExportTestDataWithAttrs>(dataList);
        // ExcelFileResultを使用してエクスポート
        return new ExcelFileResult(excelDataBytes);
    }

    /// <summary>
    /// ストリームを使用してExcelファイルをエクスポートする
    /// </summary>
    /// <returns></returns>
    [HttpGet("ExportByStream")]
    public async Task<ActionResult> ExportByStream()
    {
        // サンプルデータを100件生成
        var dataList = GenerateSampleData(100);
        var excelExporter = new ExcelExporter();
        var excelBytes = await excelExporter.ExportAsByteArray<ExportTestDataWithAttrs>(dataList);
        var outputStream = new MemoryStream(excelBytes);
        return new ExcelFileResult(outputStream, "download_file.xlsx");
    }


    /// <summary>
    /// ジェネリックコレクションを使用してExcelファイルをエクスポートする
    /// </summary>
    /// <returns></returns>
    [HttpGet("ExportByList")]
    public async Task<ActionResult> ExportByList()
    {
        var dataList = GenerateSampleData(100);
        return new ExcelFileResult<ExportTestDataWithAttrs>(dataList, "export_data.xlsx");
    }

    private List<ExportTestDataWithAttrs> GenerateSampleData(int count)
    {
        // 実際の実装では、ここでデータを生成します。
        // この例では、GenFu.GenFu.ListOf<...> の代わりに、
        // 任意のデータ生成ロジックを使用します。
        return new List<ExportTestDataWithAttrs>();
    }
}

上記の通り、Magicodes.IE.Excel.AspNetCoreを参照すると、エクスポートが非常に簡単になります。重要な点は以下の通りです。

  • ExcelFileResultを使用するには、パッケージMagicodes.IE.Excel.AspNetCoreを参照する必要があります。
  • ExcelFileResultActionResultを継承しており、現在、**バイト配列、ストリーム、およびジェネリックコレクション**をパラメータとして受け取るExcelファイルのダウンロードをサポートしています。
  • ダウンロードファイル名を渡すことができ、パラメータ名はfileNameです。渡されない場合は、一意のファイル名が自動的に生成されます。

核心実装

Magicodes.IE.Excel.AspNetCoreでは、カスタムのActionResultであるExcelFileResultが追加されています。核心となるコードは以下の通りです。

/// <summary>
/// Excelファイル用のActionResult
/// </summary>
/// <typeparam name="T"></typeparam>
public class ExcelFileResult<T> : ExcelFileResultBase where T : class, new()
{
    /// <summary>
    ///
    /// </summary>
    /// <param name="exportData"></param>
    /// <param name="fileName"></param>
    public ExcelFileResult(ICollection<T> exportData, string fileName = null)
    {
        FileName = fileName;
        ExportData = exportData;
    }

    public string FileName { get; }
    public ICollection<T> ExportData { get; }

    public async override Task ExecuteAsync(ActionContext actionContext)
    {
        var excelExporter = new ExcelExporter();
        var excelDataBytes = await excelExporter.ExportAsByteArray(ExportData);
        var outputStream = new MemoryStream(excelDataBytes);
        await SendExcelFileAsync(actionContext, outputStream, FileName);
    }
}

/// <summary>
///
/// </summary>
public class ExcelFileResult : ExcelFileResultBase
{
    /// <summary>
    ///
    /// </summary>
    /// <param name="fileStream"></param>
    /// <param name="fileName"></param>
    public ExcelFileResult(Stream fileStream, string fileName = null)
    {
        FileStream = fileStream;
        FileName = fileName;
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="excelDataBytes"></param>
    /// <param name="fileName"></param>
    public ExcelFileResult(byte[] excelDataBytes, string fileName = null)
    {
        FileStream = new MemoryStream(excelDataBytes);
        FileName = fileName;
    }


    public Stream FileStream { get; protected set; }
    public string FileName { get; protected set; }


    public async override Task ExecuteAsync(ActionContext actionContext)
    {
        await SendExcelFileAsync(actionContext, FileStream, FileName);
    }
}

/// <summary>
/// 基底クラス
/// </summary>
public class ExcelFileResultBase : ActionResult
{
    /// <summary>
    /// Excelファイルをダウンロードさせる
    /// </summary>
    /// <param name="actionContext"></param>
    /// <param name="stream"></param>
    /// <param name="downloadFileName"></param>
    /// <returns></returns>
    protected virtual async Task SendExcelFileAsync(ActionContext actionContext,
                                                        Stream stream,
                                                        string downloadFileName)
    {
        var httpResponse = actionContext.HttpContext.Response;
        httpResponse.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

        if (downloadFileName == null)
        {
            downloadFileName = Guid.NewGuid().ToString("N") + ".xlsx";
        }

        if (string.IsNullOrEmpty(Path.GetExtension(downloadFileName)))
        {
            downloadFileName += ".xlsx";
        }

        actionContext.HttpContext.Response.Headers.Add("Content-Disposition", new[] {
            "attachment; filename=" + HttpUtility.UrlEncode(downloadFileName)
        });
        await stream.CopyToAsync(actionContext.HttpContext.Response.Body);
    }
}

タグ: Magicodes.IE ASP.NET Core Excel C# ExcelExporter

5月25日 06:03 投稿