今日のデータベースの世界では、グラフやグラフを通じて複雑な情報を視覚化することは不可欠となっていますが、Excelは強力なグラフ機能を提供していますが、これらの視覚要素を独立した画像として抽出する必要がある数え切れないシナリオがあります。

  • レポートとプレゼンテーションにグラフを組み込む
  • ウェブアプリケーションに組み込まれたビジュアル化
  • 全てのスプレッドシートを配布せずに洞察を共有する
  • グラフイラストでドキュメンタリーを作成する
  • ビジネスインテリジェンスダッシュボードのためのダイナミックなビジュアルコンテンツの生成

Aspose.Cells for .NET は、Microsoft Excel のインストールを必要とせずに Excel グラフを高品質の画像にプログラム的に変換するための強力なソリューションを提供します。

なぜグラフ変換のための Aspose.Cells を選択するのですか?

Excel 自動化への伝統的なアプローチは、以下のおかげで生産環境で問題となる可能性があります。

  • セキュリティ脆弱性
  • 運用複雑さ
  • ライセンス課題
  • パフォーマンスボトル
  • 安定問題

Aspose.Cells は、Excel ファイルのサーバーサイド処理に特別に設計された専用 API を提供し、優れたパフォーマンスと信頼性を提供します。

始めに

例に浸る前に、あなたが持っていることを確認してください:

  • ダウンロード・インストール ASPOSE.CELL を .NET に
  • 引用を追加しました Aspose.Cells.dll あなたのプロジェクト
  • 必要な名称スペース:
using Aspose.Cells;
using Aspose.Cells.Charts;
using Aspose.Cells.Rendering;

基本図 イメージ変換

まずは、ワークシートのすべてのグラフを画像に変換する単純な例から始まります C# Excel Chart to Image:

// Load the Excel file containing charts
Workbook workbook = new Workbook("SalesReport.xlsx");

// Access the worksheet containing charts
Worksheet sheet = workbook.Worksheets[0];

// Initialize counter for unique filenames
int chartIndex = 1;

// Process each chart in the worksheet
foreach (Chart chart in sheet.Charts)
{
    // Define the output path for the image
    string outputPath = $"Chart_{chartIndex}.png";
    
    // Convert the chart to an image
    chart.ToImage(outputPath, ImageFormat.Png);
    
    Console.WriteLine($"Successfully converted chart {chartIndex} to {outputPath}");
    chartIndex++;
}

カスタムオプションで画像の質を向上させる

プロのアプリケーションでは、頻繁に輸出された画像の品質と外観をコントロールする必要があります. これは Java Excel Chart to Image テクニックを使用して達成できます:

// Load the workbook containing charts
Workbook workbook = new Workbook("FinancialDashboard.xlsx");
Worksheet sheet = workbook.Worksheets["Performance Metrics"];

// Create image options with high resolution
ImageOrPrintOptions imageOptions = new ImageOrPrintOptions
{
    HorizontalResolution = 300,
    VerticalResolution = 300,
    ImageFormat = ImageFormat.Jpeg,
    Quality = 95 // Higher quality JPEG compression
};

// Access a specific chart (e.g., the first chart)
Chart revenueChart = sheet.Charts[0];

// Convert with custom options
revenueChart.ToImage("Revenue_Trends_HQ.jpg", imageOptions);

複数のグラフを異なる形式で変換する

異なる使用ケースは異なる画像フォーマットを必要とする可能性があります. ここでは、様々なフォーマットにグラフを輸出する方法です:

// Load the Excel workbook
Workbook workbook = new Workbook("QuarterlyReport.xlsx");
Worksheet sheet = workbook.Worksheets["Sales Analysis"];

// Initialize counter for unique filenames
int idx = 0;

// Process each chart with custom options for different formats
foreach (Chart chart in sheet.Charts)
{
    // Create image options
    ImageOrPrintOptions imgOpts = new ImageOrPrintOptions();
    
    // Configure different settings based on chart index
    switch (idx % 3)
    {
        case 0: // PNG format with transparency
            imgOpts.ImageFormat = ImageFormat.Png;
            chart.ToImage($"Chart_{idx}_transparent.png", imgOpts);
            break;
            
        case 1: // JPEG format with high quality
            imgOpts.ImageFormat = ImageFormat.Jpeg;
            imgOpts.Quality = 100;
            chart.ToImage($"Chart_{idx}_high_quality.jpg", imgOpts);
            break;
            
        case 2: // SVG format for vector graphics
            imgOpts.ImageFormat = ImageFormat.Svg;
            chart.ToImage($"Chart_{idx}_vector.svg", imgOpts);
            break;
    }
    
    ++idx;
}

Advanced Chart Rendering オプション

レディングプロセスの正確なコントロールが必要な場合、Aspose.Cellsは幅広いカスタマイズ機能を提供します。

// Load the source workbook
Workbook workbook = new Workbook("MarketingAnalytics.xlsx");
Worksheet sheet = workbook.Worksheets["Campaign Performance"];

// Get reference to a specific chart
Chart campaignChart = sheet.Charts[0];

// Create advanced rendering options
ImageOrPrintOptions renderOptions = new ImageOrPrintOptions
{
    // Set high resolution for print-quality output
    HorizontalResolution = 600,
    VerticalResolution = 600,
    
    // Control image appearance
    ImageFormat = ImageFormat.Png,
    OnlyArea = false, // Include the entire chart area
    
    // Set custom dimensions (if needed)
    CustomPrintPageWidth = 800,
    CustomPrintPageHeight = 600,
    
    // Enable text rendering hints for smoother text
    TextRenderingHint = TextRenderingHint.AntiAlias,
    
    // Apply print settings from the workbook
    PrintingPage = PrintingPageType.Default
};

// Convert chart with advanced options
campaignChart.ToImage("Campaign_Performance_Print_Quality.png", renderOptions);

複数のワークシートからバッチ処理グラフ

企業アプリケーションでは、複数のワークシートを介してグラフを処理する必要があるかもしれません。

// Load the source Excel file
Workbook workbook = new Workbook("AnnualReport.xlsx");

// Create a directory for output images
string outputDir = "ChartImages";
Directory.CreateDirectory(outputDir);

// Process charts from all worksheets in the workbook
foreach (Worksheet sheet in workbook.Worksheets)
{
    // Skip worksheets without charts
    if (sheet.Charts.Count == 0)
        continue;
        
    Console.WriteLine($"Processing {sheet.Charts.Count} charts from worksheet '{sheet.Name}'");
    
    // Process each chart in the current worksheet
    for (int i = 0; i < sheet.Charts.Count; i++)
    {
        // Get the chart
        Chart chart = sheet.Charts[i];
        
        // Create a descriptive filename
        string sanitizedSheetName = string.Join("_", sheet.Name.Split(Path.GetInvalidFileNameChars()));
        string outputPath = Path.Combine(outputDir, $"{sanitizedSheetName}_Chart_{i+1}.png");
        
        // Define image options
        ImageOrPrintOptions imgOptions = new ImageOrPrintOptions
        {
            HorizontalResolution = 300,
            VerticalResolution = 300
        };
        
        // Convert and save the chart
        chart.ToImage(outputPath, imgOptions);
        
        Console.WriteLine($"  - Saved chart {i+1} to {outputPath}");
    }
}

グラフをWebアプリケーションのためのSVGに変換する

SVG (Scalable Vector Graphics) は、Web アプリケーションのための優れたフォーマットであり、あらゆる解像度でグラフがクラッシュに見えることを保証します。

// Load the workbook
Workbook workbook = new Workbook("WebDashboard.xlsx");
Worksheet sheet = workbook.Worksheets["Performance Metrics"];

// Configure SVG export options
ImageOrPrintOptions svgOptions = new ImageOrPrintOptions
{
    ImageFormat = ImageFormat.Svg,
    SaveFormat = SaveFormat.Svg
};

// Export all charts to SVG with viewBox attribute for responsive display
for (int i = 0; i < sheet.Charts.Count; i++)
{
    Chart chart = sheet.Charts[i];
    
    // Export with viewBox attribute
    chart.ToImage($"WebChart_{i+1}.svg", svgOptions);
}

大型ワークブックの変換進歩の監視

複数のグラフを含むワークブックに取り組むときは、変換の進歩を追跡するのに役立ちます。

// Load a large workbook with many charts
Workbook workbook = new Workbook("EnterpriseReports.xlsx");

// Create a custom stream provider to monitor progress
class ChartConversionStreamProvider : IStreamProvider
{
    private int _totalCharts;
    private int _processedCharts = 0;
    
    public ChartConversionStreamProvider(int totalCharts)
    {
        _totalCharts = totalCharts;
    }
    
    public Stream GetStream(string chartName, StreamType streamType)
    {
        // Create output stream
        string outputPath = $"Chart_{chartName}.png";
        Stream stream = new FileStream(outputPath, FileMode.Create);
        
        // Update and report progress
        _processedCharts++;
        double progressPercentage = (_processedCharts / (double)_totalCharts) * 100;
        Console.WriteLine($"Converting chart {_processedCharts} of {_totalCharts}: {progressPercentage:F1}% complete");
        
        return stream;
    }
    
    public void CloseStream(Stream stream)
    {
        if (stream != null)
        {
            stream.Close();
        }
    }
}

// Count total charts across all worksheets
int totalCharts = 0;
foreach (Worksheet sheet in workbook.Worksheets)
{
    totalCharts += sheet.Charts.Count;
}

// Create stream provider and options
ChartConversionStreamProvider streamProvider = new ChartConversionStreamProvider(totalCharts);
ImageOrPrintOptions options = new ImageOrPrintOptions
{
    HorizontalResolution = 300,
    VerticalResolution = 300
};

// Process each chart with progress tracking
int chartIndex = 0;
foreach (Worksheet sheet in workbook.Worksheets)
{
    foreach (Chart chart in sheet.Charts)
    {
        // Generate unique chart name
        string chartName = $"{sheet.Name}_Chart_{chartIndex++}";
        
        // Convert using stream provider
        chart.ToImage(streamProvider.GetStream(chartName, StreamType.Output), options);
    }
}

図から画像に変換するための最良の実践

Excel グラフを画像に変換する際の最適な結果を得るには、以下の推奨事項を検討してください。

  • 目的に基づく解像度の調整:印刷材料のための高解像度(300+DPI)を使用し、ウェブディスプレイのための低解像度を使用します。
  • 正しいフォーマットを選択する:透明なグラフのためのPNG、写真のためのJPEG、WebアプリケーションのためのSVGを使用します。
  • Test Different Quality Settings: ファイルサイズと画像の品質をバランス付ける、特にJPEG圧縮の場合。
  • フィルネームを修復する:ワークシート名からフィルネームを生成するとき、不適切な文字を削除します。
  • Implement Progress Tracking: 多くのグラフを含むワークブックでは、ユーザーに進歩のフィードバックを提供します。
  • リソースを適切に処理する:メモリの漏れを防ぐために、ストリームを閉じ、オブジェクトを配置する。

結論

Aspose.Cells for .NET は、Excel グラフをさまざまな画像形式にプログラミング的に変換するための強力で柔軟なソリューションを提供します. 印刷材料のための高解像度画像、Web アプリケーション向けの最適化された図面、または反応性のデザイン用のベクトル SVG が必要であるかどうかにかかわらず、Speed.cells には、Microsoft Excel インストールを必要とせずに一貫性のある高品質の結果が提供されます。

この記事で示された例や最良の実践に従って、グラフから画像への変換機能を .NET アプリケーションに統合し、データビジュアル化のワークフローを強化し、さまざまなプラットフォームやメディアを通じて Excel ベースのビジュアル化を無制限に共有することができます。

More in this category