Excel 차트와 잎을 PNG 이미지로 변환하는 방법

Excel 차트와 잎을 PNG 이미지로 변환하는 방법

이 기사는 .NET 응용 프로그램에서 Aspose.Cells LowCode ImageConverter를 사용하여 Excel 차트 및 워크시트를 PNG 이미지로 변환하는 방법을 보여줍니다.Imager는 Excel 내부 구조에 대한 광범위한 코딩이나 깊은 지식을 필요로하지 않고 고품질의 이미지로서 Excel 시각 요소를 수출하는 유연한 접근 방식을 제공합니다.

현실 세계 문제

보고 디자이너 및 비즈니스 분석가들은 종종 프레젠테이션, 문서 및 웹 응용 프로그램에 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 참조 .

 한국어