この記事では、Web アプリケーションにおける Aspose.Cells LowCode Converters を使用してメモリ内の Excel フォーマット変換を実施する方法を示しています. これらのコンバーターは、広範囲のコードやディスクへの暫定ファイルの保存を必要とせず、Excel 形式の変革に対処するための簡素化されたアプローチを提供し、ウェブおよび SaaS 環境に最適です。

現実世界問題

ウェブアプリケーションは、頻繁にユーザーがアップロードするExcelファイルを処理し、PDF、HTML、またはJSONなどのさまざまなフォーマットに変換して表示、共有、データ抽出する必要があります。

ソリューション概要

Aspose.Cells LowCode Converters を使用すると、メモリ内のすべての変換を実行することによって、この課題を効率的に解決することができます このソリューションは、複雑なファイルシステム操作なしに安全でスケール可能なドキュメント処理機能を実施する必要があるウェブ開発者や SaaS アーキテクチャーにとって理想的です。

原則

解決策を実施する前に、あなたが持っていることを確認してください:

  • Visual Studio 2019 以降
  • .NET 6.0 またはそれ以降(NET Framework 4.6.2+ と互換性がある)
  • NuGet を介してインストールされた .NET パッケージのための Aspose.Cells
  • ウェブアプリケーションプロジェクト(ASP.NET Core MVC、Web APIなど)
PM> Install-Package Aspose.Cells

ステップ・ステップ・実施

ステップ1:インストールおよび設定 Aspose.Cells

あなたのウェブプロジェクトに Aspose.Cells パッケージを追加し、必要な名称スペースを含む:

using Aspose.Cells;
using Aspose.Cells.LowCode;
using Aspose.Cells.Rendering;
using System.IO;

ステップ2:ファイル変換を処理するためのコントローラー方法を作成する

API エンド ポイントまたはコントローラー メソッドを設定して、ファイルアップロードを受け入れ、変換されたフォーマットを返します。

[HttpPost("convert-to-pdf")]
public IActionResult ConvertToPdf(IFormFile excelFile)
{
    if (excelFile == null || excelFile.Length == 0)
        return BadRequest("No file uploaded");
        
    // Continue with conversion process
}

ステップ3:メモリコンバージョン論理の実装

アップロードされたファイルを処理し、完全にメモリに変換します:

// Read the uploaded file into memory
using var inputStream = new MemoryStream();
excelFile.CopyTo(inputStream);
inputStream.Position = 0;

// Configure the conversion options
LowCodeLoadOptions loadOptions = new LowCodeLoadOptions();
loadOptions.InputStream = inputStream;

// Create output memory stream for the converted file
using var outputStream = new MemoryStream();

// Configure save options for PDF
LowCodePdfSaveOptions saveOptions = new LowCodePdfSaveOptions();
PdfSaveOptions pdfOptions = new PdfSaveOptions();
pdfOptions.OnePagePerSheet = true;
saveOptions.PdfOptions = pdfOptions;
saveOptions.OutputStream = outputStream;

// Execute the conversion
PdfConverter.Process(loadOptions, saveOptions);

ステップ4:変換されたファイルをクライアントに返す

ダウンロード可能な回答として変換されたファイルを返す:

// Reset the position of output stream
outputStream.Position = 0;

// Return as downloadable file
return File(outputStream.ToArray(), "application/pdf", "converted-document.pdf");

ステップ5:異なる変換タイプの実施

HTML、JSON、および画像などの他の変換形式の方法を追加する:

// HTML conversion
public MemoryStream ConvertToHtml(MemoryStream inputStream)
{
    LowCodeLoadOptions loadOptions = new LowCodeLoadOptions();
    loadOptions.InputStream = inputStream;
    
    LowCodeHtmlSaveOptions saveOptions = new LowCodeHtmlSaveOptions();
    HtmlSaveOptions htmlOptions = new HtmlSaveOptions();
    htmlOptions.ExportImagesAsBase64 = true; // For fully self-contained HTML
    saveOptions.HtmlOptions = htmlOptions;
    
    var outputStream = new MemoryStream();
    saveOptions.OutputStream = outputStream;
    
    HtmlConverter.Process(loadOptions, saveOptions);
    outputStream.Position = 0;
    return outputStream;
}

// JSON conversion
public MemoryStream ConvertToJson(MemoryStream inputStream)
{
    LowCodeLoadOptions loadOptions = new LowCodeLoadOptions();
    loadOptions.InputStream = inputStream;
    
    LowCodeSaveOptions saveOptions = new LowCodeSaveOptions();
    var outputStream = new MemoryStream();
    saveOptions.OutputStream = outputStream;
    
    JsonConverter.Process(loadOptions, saveOptions);
    outputStream.Position = 0;
    return outputStream;
}

ステップ6:Webシナリオのエラー処理の実施

ウェブ環境に適切なエラー処理を追加する:

try
{
    // Process execution code
    PdfConverter.Process(loadOptions, saveOptions);
    return File(outputStream.ToArray(), "application/pdf", "converted-document.pdf");
}
catch (Exception ex)
{
    // Log the error
    _logger.LogError(ex, "Error converting Excel file to PDF");
    
    // Return appropriate HTTP response
    return StatusCode(500, "An error occurred during file conversion. Please try again.");
}

ステップ7:Webアプリケーションパフォーマンスの最適化

ウェブ環境のためのこれらの最適化テクニックを検討する:

// Implement an async version for better scalability
[HttpPost("convert-to-pdf-async")]
public async Task<IActionResult> ConvertToPdfAsync(IFormFile excelFile)
{
    if (excelFile == null || excelFile.Length == 0)
        return BadRequest("No file uploaded");
        
    using var inputStream = new MemoryStream();
    await excelFile.CopyToAsync(inputStream);
    inputStream.Position = 0;
    
    // Perform conversion on a background thread to free up web server threads
    return await Task.Run(() => {
        try
        {
            using var outputStream = new MemoryStream();
            // Conversion code as before
            PdfConverter.Process(loadOptions, saveOptions);
            
            return File(outputStream.ToArray(), "application/pdf", "converted-document.pdf");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in async conversion");
            throw;
        }
    });
}

ステップ8:完璧な実施例

以下は、フォーマット変換のためのWeb API コントローラーの完全な作業例です:

[ApiController]
[Route("api/[controller]")]
public class ExcelConverterController : ControllerBase
{
    private readonly ILogger<ExcelConverterController> _logger;
    
    public ExcelConverterController(ILogger<ExcelConverterController> logger)
    {
        _logger = logger;
    }
    
    [HttpPost("convert")]
    public async Task<IActionResult> ConvertExcelFile(IFormFile file, [FromQuery] string format)
    {
        if (file == null || file.Length == 0)
            return BadRequest("Please upload a file");
            
        using var inputStream = new MemoryStream();
        await file.CopyToAsync(inputStream);
        inputStream.Position = 0;
        
        // Initialize options
        LowCodeLoadOptions loadOptions = new LowCodeLoadOptions();
        loadOptions.InputStream = inputStream;
        
        using var outputStream = new MemoryStream();
        
        try
        {
            switch (format?.ToLower())
            {
                case "pdf":
                    LowCodePdfSaveOptions pdfOptions = new LowCodePdfSaveOptions();
                    pdfOptions.OutputStream = outputStream;
                    PdfConverter.Process(loadOptions, pdfOptions);
                    return ReturnFile(outputStream, "application/pdf", "converted.pdf");
                    
                case "html":
                    LowCodeHtmlSaveOptions htmlOptions = new LowCodeHtmlSaveOptions();
                    htmlOptions.OutputStream = outputStream;
                    HtmlConverter.Process(loadOptions, htmlOptions);
                    return ReturnFile(outputStream, "text/html", "converted.html");
                    
                case "json":
                    LowCodeSaveOptions jsonOptions = new LowCodeSaveOptions();
                    jsonOptions.OutputStream = outputStream;
                    JsonConverter.Process(loadOptions, jsonOptions);
                    return ReturnFile(outputStream, "application/json", "converted.json");
                    
                case "png":
                    LowCodeImageSaveOptions imgOptions = new LowCodeImageSaveOptions();
                    ImageOrPrintOptions imageTypeOptions = new ImageOrPrintOptions();
                    imageTypeOptions.ImageType = Aspose.Cells.Drawing.ImageType.Png;
                    imgOptions.ImageOptions = imageTypeOptions;
                    imgOptions.OutputStream = outputStream;
                    ImageConverter.Process(loadOptions, imgOptions);
                    return ReturnFile(outputStream, "image/png", "converted.png");
                    
                default:
                    return BadRequest("Unsupported format. Please use: pdf, html, json, or png");
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error converting file to {Format}", format);
            return StatusCode(500, "An error occurred during conversion");
        }
    }
    
    private FileContentResult ReturnFile(MemoryStream stream, string contentType, string fileName)
    {
        stream.Position = 0;
        return File(stream.ToArray(), contentType, fileName);
    }
}

ケースとアプリケーションの使用

ウェブベースのドキュメントビューシステム

ユーザーがエクセルファイルをアップロードし、Excelソフトウェアを必要とせずにHTMLまたはPDFとしてすぐに表示することができます。これは、プラットフォーム間の互換性とモバイルフレンドリーなドキュメントを直接ブラウザで表示できます。

SaaS データ処理プラットフォーム

プロセスは、データベースの統合のためにJSONに変換してExcelデータをアップロードし、その後、さまざまなフォーマット(PDF、HTML)のレポートを生成します。

APIベースのドキュメント変換サービス

あなたのエコシステム内の他のアプリケーションのためのExcelフォーマット変換を処理する専門のマイクロサービスまたはAPIエンドポイントを構築し、サービス全体で一貫性を維持する中心化されたコンバージョン機能を提供します。

共通の課題と解決策

課題1:大ファイル処理

ソリューション: メモリ制限を超えるファイルの場合、スイッチ処理を実施するか、サーバー側のストリーミングを使用する場合:

// For large files, consider setting timeout and memory limits
[RequestSizeLimit(100_000_000)] // 100MB limit
[RequestFormLimits(MultipartBodyLengthLimit = 100_000_000)]
public async Task<IActionResult> ConvertLargeFile(IFormFile file)
{
    // Implementation with resource monitoring
}

チャレンジ2:コンテストリクエストマネジメント

ソリューション: サーバーの過剰負荷を防ぐために、クイーリングおよびリソースストレッチを実施する:

// Use a semaphore to limit concurrent conversions
private static SemaphoreSlim _conversionSemaphore = new SemaphoreSlim(5); // Max 5 concurrent

public async Task<IActionResult> ConvertWithThrottling(IFormFile file)
{
    await _conversionSemaphore.WaitAsync();
    try
    {
        // Conversion code
    }
    finally
    {
        _conversionSemaphore.Release();
    }
}

チャレンジ3:セキュリティ問題

ソリューション: 入力ファイルの適切な認証および衛生を実施する:

private bool ValidateExcelFile(IFormFile file)
{
    // Check file extension
    var extension = Path.GetExtension(file.FileName).ToLowerInvariant();
    if (extension != ".xlsx" && extension != ".xls" && extension != ".xlsm")
        return false;
        
    // Verify file signature/magic bytes
    using var headerStream = new MemoryStream();
    file.OpenReadStream().CopyTo(headerStream, 8); // Read first 8 bytes
    byte[] headerBytes = headerStream.ToArray();
    
    // Check for Excel file signatures
    return IsValidExcelFileSignature(headerBytes);
}

パフォーマンス考慮

  • すべての I/O 作業のための非同期処理を使用して、Web サーバーのテープブロックを防ぐ
  • 処理負荷を減らすために頻繁に変換された文書のキャッシングを実施することを検討する
  • 高流量アプリケーションでは、変換処理のための専用の背景サービスを実施します。

ベストプラクティス

  • メモリストリームのオブジェクトを常に利用して、特に長期にわたるウェブアプリケーションにおいて、記憶漏れを防ぐ。
  • あなたのサーバーのリソースに適したファイルサイズの制限を実施する
  • メトリックとモニタリングを使用して変換時間とリソースの使用を追跡する
  • 乱用を防ぐために変換端点の利率制限メカニズムの導入を検討する

高度なシナリオ

より複雑な要件のために、これらの先進的な実施を検討してください:

シナリオ1:バッチ処理複数の変換

[HttpPost("batch-convert")]
public async Task<IActionResult> BatchConvert(List<IFormFile> files, string format)
{
    if (files == null || !files.Any())
        return BadRequest("No files uploaded");
        
    var results = new List<ConversionResult>();
    
    foreach (var file in files)
    {
        using var inputStream = new MemoryStream();
        await file.CopyToAsync(inputStream);
        inputStream.Position = 0;
        
        using var outputStream = new MemoryStream();
        try
        {
            LowCodeLoadOptions loadOptions = new LowCodeLoadOptions();
            loadOptions.InputStream = inputStream;
            
            LowCodeSaveOptions saveOptions = new LowCodeSaveOptions();
            saveOptions.OutputStream = outputStream;
            
            switch (format.ToLower())
            {
                case "pdf":
                    PdfConverter.Process(loadOptions, saveOptions);
                    break;
                // Other formats...
            }
            
            results.Add(new ConversionResult { 
                FileName = file.FileName,
                Success = true,
                Data = Convert.ToBase64String(outputStream.ToArray())
            });
        }
        catch (Exception ex)
        {
            results.Add(new ConversionResult { 
                FileName = file.FileName,
                Success = false,
                ErrorMessage = ex.Message
            });
        }
    }
    
    return Ok(results);
}

シナリオ2:変換前のダイナミックスプレッドシート操作

[HttpPost("modify-and-convert")]
public async Task<IActionResult> ModifyAndConvert(IFormFile file, 
    [FromQuery] string format,
    [FromBody] SpreadsheetModificationRequest modRequest)
{
    using var inputStream = new MemoryStream();
    await file.CopyToAsync(inputStream);
    inputStream.Position = 0;
    
    // First load the workbook to modify it
    Workbook workbook = new Workbook(inputStream);
    
    // Apply the requested modifications
    var worksheet = workbook.Worksheets[modRequest.WorksheetIndex];
    foreach (var cellMod in modRequest.CellModifications)
    {
        worksheet.Cells[cellMod.CellReference].PutValue(cellMod.NewValue);
    }
    
    // Now prepare for conversion
    using var modifiedStream = new MemoryStream();
    workbook.Save(modifiedStream, SaveFormat.Xlsx);
    modifiedStream.Position = 0;
    
    // Convert using LowCode converters
    LowCodeLoadOptions loadOptions = new LowCodeLoadOptions();
    loadOptions.InputStream = modifiedStream;
    
    using var outputStream = new MemoryStream();
    LowCodePdfSaveOptions saveOptions = new LowCodePdfSaveOptions();
    saveOptions.OutputStream = outputStream;
    
    PdfConverter.Process(loadOptions, saveOptions);
    
    outputStream.Position = 0;
    return File(outputStream.ToArray(), "application/pdf", "modified-and-converted.pdf");
}

結論

Aspose.Cells LowCode Converters を使用してメモリ内の Excel フォーマット変換を実施することで、Web 開発者は、ファイル システム依存症なしで強力なドキュメント処理機能でアプリケーションを大幅に改善することができます。このアプローチは、一時的なファイルの脆弱性を排除し、クラウドおよび SaaS アプリ用の優れた性能とスケール性を維持することによってセキュリティを劇的に向上させます。

詳しい情報や追加の例を参照してください。 Aspose.Cells.LowCode API リファレンス.

追加資源

  • Aspose.Cells SaveOptionsを実施することで、あなたの特定のニーズを満たすために変換プロセスをカスタマイズするのに役立ちます。

More in this category