Excel グラフやシートを PNG 画像に変換する方法

Excel グラフやシートを PNG 画像に変換する方法

この記事では、Aspose.Cells LowCode ImageConverter を使用して Excel グラフやワークシートを PNG 画像に変換する方法を示しています。

現実世界問題

レポートデザイナーやビジネスアナリストは、プレゼンテーション、ドキュメント、およびウェブアプリケーションにExcelベースのビジュアルを組み込む必要があります. スクリーンショットを手動で撮影したり、複雑な画像操作図書館を使用すると、不一致な品質、失われたフォーマット、そして重要な開発のトップが得られます。

ソリューション概要

Aspose.Cells LowCode ImageConverterを使用すると、この課題を最小限のコードで効率的に解決することができます このソリューションは、Excelデータから高品質のビジュアル資産をプログラム的に生成する必要があるレポートデザイナーやビジネスアナリストにとって理想的です。

原則

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

  • Visual Studio 2019 以降
  • .NET 6.0 またはそれ以降(NET Framework 4.6.2+ と互換性がある)
  • NuGet を介してインストールされた .NET パッケージのための Aspose.Cells
  • C#プログラミングの基本的な理解

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:入力データの準備

PNG 画像に変換したいグラフやワークシートを含む Excel ファイルを特定します。

// Define the path to your Excel file
string excelFilePath = "reports/quarterly_sales.xlsx";

// Ensure the directory for output exists
Directory.CreateDirectory("result");

ステップ3: ImageConverter オプションを設定する

ImageConverter プロセスのオプションをあなたの要求に応じて設定します:

// Basic usage - convert the entire workbook
ImageConverter.Process(excelFilePath, "result/BasicOutput.png");

// Advanced configuration
LowCodeLoadOptions loadOptions = new LowCodeLoadOptions();
loadOptions.InputFile = excelFilePath;

LowCodeImageSaveOptions saveOptions = new LowCodeImageSaveOptions();
ImageOrPrintOptions imageOptions = new ImageOrPrintOptions();
imageOptions.ImageType = Aspose.Cells.Drawing.ImageType.Png;
imageOptions.Quality = 100; // Set the quality of the output image
imageOptions.OnePagePerSheet = true; // Each sheet on a separate image
saveOptions.ImageOptions = imageOptions;

ステップ4: ImageConverter プロセスを実行する

ImageConverter オペレーションを構成されたオプションで実行する:

// Basic execution
ImageConverter.Process(loadOptions, saveOptions);

// Advanced execution with custom file naming
LowCodeSaveOptionsProviderOfPlaceHolders fileNameProvider = new LowCodeSaveOptionsProviderOfPlaceHolders(
    "result/Chart${SheetIndexPrefix}${SheetIndex}_${SplitPartIndex}.png");
fileNameProvider.SheetIndexOffset = 1;
fileNameProvider.SheetIndexPrefix = "S";
fileNameProvider.SplitPartIndexOffset = 1;

ImageConverter.Process(loadOptions, saveOptions, fileNameProvider);

ステップ5:出力処理

プロセスおよびあなたのアプリケーションに必要なように生成されたPNG画像を使用する:

// Verify the output files exist
if (File.Exists("result/ChartS1_1.png"))
{
    Console.WriteLine("Chart image successfully created!");
    
    // Implement your logic to use the image files
    // For example: Copy to a web server directory
    // File.Copy("result/ChartS1_1.png", "wwwroot/images/chart1.png");
}

ステップ6:エラー処理の実施

強力な操作を確保するために、適切なエラー処理を追加します:

try
{
    // Configure load options
    LowCodeLoadOptions loadOptions = new LowCodeLoadOptions();
    loadOptions.InputFile = excelFilePath;
    
    // Configure save options
    LowCodeImageSaveOptions saveOptions = new LowCodeImageSaveOptions();
    ImageOrPrintOptions imageOptions = new ImageOrPrintOptions();
    imageOptions.ImageType = Aspose.Cells.Drawing.ImageType.Png;
    saveOptions.ImageOptions = imageOptions;
    
    // Execute conversion
    ImageConverter.Process(loadOptions, saveOptions);
    
    Console.WriteLine("Conversion completed successfully.");
}
catch (Exception ex)
{
    // Error handling and logging
    Console.WriteLine($"Error during conversion: {ex.Message}");
    // Log the error to your logging system
    // Consider implementing retry logic for transient issues
}

ステップ7:パフォーマンスの最適化

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

  • 高容量処理のためのメモリストリームを使用してファイル I/O 過剰を避ける
  • 複数のグラフまたはワークシートのためのパラレル処理の実施
  • 画像の品質設定を適切な品質とファイルサイズのバランスに調整する
// Using memory streams for programmatic use without file I/O
using (MemoryStream outputStream = new MemoryStream())
{
    LowCodeLoadOptions loadOptions = new LowCodeLoadOptions();
    loadOptions.InputFile = excelFilePath;
    
    LowCodeImageSaveOptions saveOptions = new LowCodeImageSaveOptions();
    ImageOrPrintOptions imageOptions = new ImageOrPrintOptions();
    imageOptions.ImageType = Aspose.Cells.Drawing.ImageType.Png;
    
    // For web use, might want lower quality/size
    imageOptions.Quality = 85;
    saveOptions.ImageOptions = imageOptions;
    saveOptions.OutputStream = outputStream;
    
    ImageConverter.Process(loadOptions, saveOptions);
    
    // Use the stream directly (e.g., with web responses)
    byte[] imageBytes = outputStream.ToArray();
    
    // Example: save to file from memory stream
    File.WriteAllBytes("result/OptimizedChart.png", imageBytes);
}

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

以下は、プロセス全体を示す完全な作業例です。

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

namespace ExcelChartToPngConverter
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // Set up directories
                Directory.CreateDirectory("result");
                
                // Define source Excel file
                string excelFilePath = "quarterly_sales.xlsx";
                
                Console.WriteLine("Starting Excel chart conversion...");
                
                // Basic conversion - entire workbook
                ImageConverter.Process(excelFilePath, "result/FullWorkbook.png");
                
                // Advanced conversion with options
                LowCodeLoadOptions loadOptions = new LowCodeLoadOptions();
                loadOptions.InputFile = excelFilePath;
                
                LowCodeImageSaveOptions saveOptions = new LowCodeImageSaveOptions();
                ImageOrPrintOptions imageOptions = new ImageOrPrintOptions();
                imageOptions.ImageType = Aspose.Cells.Drawing.ImageType.Png;
                imageOptions.Quality = 100;
                imageOptions.OnePagePerSheet = true;
                saveOptions.ImageOptions = imageOptions;
                
                // Custom file naming pattern for multi-sheet output
                LowCodeSaveOptionsProviderOfPlaceHolders fileNameProvider = 
                    new LowCodeSaveOptionsProviderOfPlaceHolders(
                        "result/Report${SheetIndexPrefix}${SheetIndex}_${SplitPartIndex}.png");
                fileNameProvider.SheetIndexOffset = 1;
                fileNameProvider.SheetIndexPrefix = "S";
                fileNameProvider.SplitPartIndexOffset = 1;
                
                // Execute conversion with custom naming
                ImageConverter.Process(loadOptions, saveOptions, fileNameProvider);
                
                // For specific sheet only conversion
                saveOptions = new LowCodeImageSaveOptions();
                imageOptions = new ImageOrPrintOptions();
                imageOptions.ImageType = Aspose.Cells.Drawing.ImageType.Png;
                imageOptions.PageIndex = 0; // First sheet only
                saveOptions.ImageOptions = imageOptions;
                saveOptions.OutputFile = "result/FirstSheetOnly.png";
                
                ImageConverter.Process(loadOptions, saveOptions);
                
                Console.WriteLine("Conversion completed successfully!");
                Console.WriteLine("Output files located in 'result' directory.");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error occurred: {ex.Message}");
                Console.WriteLine(ex.StackTrace);
            }
        }
    }
}

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

企業報告システム

金融アナリストは、実行プレゼンテーションやダッシュボードに含まれるために Excel レポートから自動的にビジュアル資産を生成することができます. これは手動スクリーンショットの撮影を排除し、ソースデータを正確に表す一貫した高品質の視覚化を保証します。

データ統合作業流

統合ワークフローは、自動的にPDFレポート、ウェブポータル、または電子メール通知に含まれるために、Excelベースのグラフを画像形式に変換することができます。

自動ドキュメント処理

ドキュメント生成システムは、データ、テキスト、視覚要素を組み合わせるプロのレポートを作成するために、Excelワークブックからグラフやビジュアルをプログラム的に抽出することができます。

共通の課題と解決策

課題1:画像の高品質を維持する

ソリューション: 適切な品質設定と解像度パラメーターを備えた ImageOrPrintOptions を設定して、最適なパフォーマンスを確保します. プレゼンテーションおよび印刷材料の場合、90 以上の品質の設定を使用し、意図された使用に基づいて DPI の設定を調整することを検討します。

課題2:大規模なワークシートの処理

ソリューション: ImageOrPrintOptions.PageIndex と PageCount の特性を使用して、大きなワークシートの特定のパーツを処理します。

課題3:周囲の不一致なレンダー

ソリューション: Excel ファイルで使用されるフォントがサーバーで利用可能であるか、または Aspose.Cells のフォトの置き換え設定を使用することを確認します。

パフォーマンス考慮

  • ファイル I/O の代わりにメモリストリームを使用して、複数の画像をバッチプロセスで変換します。
  • 多層環境では、共有資源にアクセスする際に適切なロックメカニズムを実施します。
  • 表のサイズと複雑さを考慮して、品質オプションを設定する - より高い複合性は、より多くの処理リソースを必要とします。

ベストプラクティス

  • 繰り返し変換を避けるために頻繁にアクセスされるグラフのキャッシングメカニズムを実施する
  • 各画像のソースを追跡するために、出力ファイルのためのシステム的な名称コンベンションを作成します。
  • 画像出力ディレクトリにメタデータを含み、フォース Excel ファイルに戻る追跡性を維持します。
  • 処理前に入力 Excel ファイルを確認して、予想されるグラフやデータが含まれていることを確認します。
  • 成功した変換や処理中に発生する問題を追跡するための実施ログ

高度なシナリオ

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

シナリオ1:ワークシートから特定のグラフのみを抽出する

using Aspose.Cells;
using Aspose.Cells.Charts;
using Aspose.Cells.Drawing;
using System.IO;

// Load the workbook
Workbook workbook = new Workbook("reports/charts.xlsx");

// Get the first worksheet
Worksheet worksheet = workbook.Worksheets[0];

// Process each chart in the worksheet
for (int i = 0; i < worksheet.Charts.Count; i++)
{
    Chart chart = worksheet.Charts[i];
    
    // Save only specific charts based on title or other properties
    if (chart.Title.Text.Contains("Revenue"))
    {
        // Create image for this specific chart
        chart.ToImage("result/revenue_chart_" + i + ".png", new ImageOrPrintOptions
        {
            ImageType = ImageType.Png,
            HorizontalResolution = 300,
            VerticalResolution = 300
        });
    }
}

シナリオ2:マルチチャップダッシュボード画像を作成する

using Aspose.Cells;
using Aspose.Cells.Drawing;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

// Load the workbook containing charts
Workbook workbook = new Workbook("reports/dashboard_data.xlsx");

// Create a bitmap to serve as the dashboard canvas
using (Bitmap dashboardImage = new Bitmap(1200, 800))
{
    using (Graphics g = Graphics.FromImage(dashboardImage))
    {
        // Set white background
        g.Clear(Color.White);
        
        // Draw title
        using (Font titleFont = new Font("Arial", 18, FontStyle.Bold))
        {
            g.DrawString("Q2 2025 Performance Dashboard", titleFont, 
                Brushes.DarkBlue, new PointF(400, 30));
        }
        
        // Extract and place charts
        int yPosition = 100;
        for (int sheetIndex = 0; sheetIndex < 3; sheetIndex++)
        {
            // Get specific worksheet with chart
            Worksheet sheet = workbook.Worksheets[sheetIndex];
            
            if (sheet.Charts.Count > 0)
            {
                // Convert chart to image
                MemoryStream chartStream = new MemoryStream();
                sheet.Charts[0].ToImage(chartStream, new ImageOrPrintOptions
                {
                    ImageType = ImageType.Png,
                    HorizontalResolution = 150,
                    VerticalResolution = 150
                });
                
                // Load chart image
                using (Bitmap chartImage = new Bitmap(chartStream))
                {
                    // Position chart on dashboard
                    g.DrawImage(chartImage, new Rectangle(50, yPosition, 500, 300));
                    yPosition += 320;
                }
            }
        }
        
        // Save the composite dashboard image
        dashboardImage.Save("result/complete_dashboard.png", ImageFormat.Png);
    }
}

結論

Aspose.Cells LowCode ImageConverter を実装することで、Excel グラフやワークシートを高品質の PNG 画像に効率的に変換し、レポートやプレゼンテーションのためのビジュアル資産の作成を簡素化できます。

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

 日本語