오늘날의 데이터 기반 세계에서 차트와 그래픽을 통해 복잡한 정보를 시각화하는 것이 필수적이되었습니다.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;
}

고급 차트 렌더링 옵션

순서 프로세스에 대한 정확한 제어가 필요할 때, 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}");
    }
}

웹 애플리케이션을 위해 차트를 SVG로 변환

SVG (Scalable Vector Graphics)는 웹 애플리케이션을위한 훌륭한 형식이며, 차트가 어떠한 해상도에서도 크리스프처럼 보이도록합니다.

// 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, 웹 응용 프로그램을 위한 SVG를 사용하십시오.
  • 다양한 품질 설정 테스트: 파일 크기와 이미지 품질, 특히 JPEG 압축을 위해 균형.
  • 필레나임을 정화하십시오: 워크시트 이름에서 필레나임을 생성할 때 부적절한 문자를 제거합니다.
  • Implement Progress Tracking: 많은 차트가 있는 워크북은 사용자에게 진보 반응을 제공합니다.
  • 자원을 적절하게 처리하십시오 : 메모리 유출을 방지하기 위해 흐름을 가까이하고 개체를 배치하십시오.

결론

Aspose.Cells for .NET은 Excel 차트를 다양한 이미지 형식으로 프로그래밍하는 강력하고 유연한 솔루션을 제공합니다. 인쇄 자료에 대한 고해상도 이미지가 필요하든, 웹 응용 프로그램을위한 최적화 된 그래픽 또는 응답 디자인을 위한 벡터 SVG가 필요한지 여부에 관계없이, ASPOSE. Cells는 Microsoft Excel 설치를 필요로 하지 않고 일관되고 고품질의 결과를 제공 합니다.

이 기사에서 설명한 예와 최상의 관행을 따르면 차트에서 이미지로 변환 기능을 .NET 응용 프로그램에 통합하여 데이터 시각화 작업 흐름을 향상시키고 다양한 플랫폼 및 미디어를 통해 Excel 기반 시각화를 무조건 공유할 수 있습니다.

More in this category