如何将Excel图表和表格转换为PNG图像

如何将Excel图表和表格转换为PNG图像

本文展示了如何将Excel图表和工作表转换为PNG图像,使用Aspose.Cells LowCode ImageConverter在 .NET 应用程序中。

现实世界问题

报告设计师和商业分析师经常需要将以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报告中创建视觉资产,以便将其纳入执行演示文稿或图表中,从而消除手动拍摄屏幕,并确保一致、高质量的视图准确地代表源数据。

数据集成工作流

集成工作流可以自动将基于 Excel 的图表转换为图像格式,以便将其纳入 PDF 报告、网页门户或电子邮件通知。

自动文件处理

文档生成系统可以从 Excel 工作簿中编程地提取图表和图像,以创建专业报告,将数据、文本和视觉元素结合在一起。

共同挑战与解决方案

挑战1:保持高图像质量

** 解决方案:** 设置 ImageOrPrintOptions 具有适当的质量设置和分辨率参数,以确保最佳输出。 对于演示文稿和印刷材料,请使用 90 或更高的品质设置,并考虑根据所需使用来调整 DPI 的设置。

挑战2:处理大型工作表

** 解决方案:** 使用 ImageOrPrintOptions.PageIndex 和 PageCount 属性来处理大型工作表的特定部分。

挑战3:不一致的环绕环境

** 解决方案:** 确保 Excel 文件中使用的字体在服务器上可用,或者在 Aspose.Cells 中使用字母替代设置。

绩效考虑

  • 在转换多个图像时使用记忆流而不是 I/O 文件
  • 对于多层环境,在访问共享资源时实施适当的锁定机制
  • 在设置质量选项时考虑表格大小和复杂性 - 更高的复杂度需要更多的处理资源

最佳实践

  • 实施经常访问的图表的缓存机制,以避免重复转换
  • 设置输出文件的系统名称协议,以跟踪每个图像的来源
  • 在图像输出目录中包含 meta 数据以保持跟踪性返回源 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 参考 .

 中文