如何在 C# 中将工作表转换为图像

如何在 C# 中将工作表转换为图像

将单一的 Excel 工作表导入图像格式(例如 PNG、JPEG)是有用的,在创建预览、导出图表或共享单纯的视觉表格内容时,您可以使用 Aspose.Cells for .NET 将一个工作表从 Excel 工作簿转换为图像。

用例

  • 创建一个特定的工作表的预览
  • 出口格式化报告电子邮件或文档
  • 在网页或PDF中插入单页

步骤指南

步骤 1: 安装 Aspose.Cells 为 .NET

dotnet add package Aspose.Cells

步骤2:下载 Excel 文件

Workbook workbook = new Workbook("SalesData.xlsx");
Worksheet sheet = workbook.Worksheets["Q1 Report"]; // Access specific worksheet

步骤3:定义图像转换选项

ImageOrPrintOptions options = new ImageOrPrintOptions
{
    ImageType = ImageType.Png,
    OnePagePerSheet = true,
    HorizontalResolution = 200,
    VerticalResolution = 200,
    PrintingPageType = PrintingPageType.Default
};

步骤4:创建 SheetRender 对象

SheetRender renderer = new SheetRender(sheet, options);

步骤5:将每个页面转换为图像

for (int pageIndex = 0; pageIndex < renderer.PageCount; pageIndex++)
{
    string imageName = $"worksheet_q1_page_{pageIndex + 1}.png";
    renderer.ToImage(pageIndex, imageName);
}

步骤6:保存图像

此代码将自动保存每张印刷页面中的一个图像。

步骤7:可选改进

您可以使用额外的配置设置:

// Show gridlines in the output image
options.ShowGridLines = true;

// Fit all content on a single page
options.AllColumnsInOnePagePerSheet = true;

完整的例子代码

using System;
using Aspose.Cells;

class Program
{
    static void Main()
    {
        // Load the Excel workbook
        Workbook workbook = new Workbook("SalesData.xlsx");

        // Access a specific worksheet
        Worksheet sheet = workbook.Worksheets["Q1 Report"];

        // Define image rendering options
        ImageOrPrintOptions options = new ImageOrPrintOptions
        {
            ImageType = ImageType.Png,
            OnePagePerSheet = true,
            HorizontalResolution = 200,
            VerticalResolution = 200,
            PrintingPageType = PrintingPageType.Default
        };

        // Enable gridlines if desired
        options.ShowGridLines = true;

        // Render the sheet to image(s)
        SheetRender renderer = new SheetRender(sheet, options);

        for (int pageIndex = 0; pageIndex < renderer.PageCount; pageIndex++)
        {
            string imageName = $"worksheet_q1_page_{pageIndex + 1}.png";
            renderer.ToImage(pageIndex, imageName);
            Console.WriteLine($"Saved: {imageName}");
        }

        Console.WriteLine("Worksheet successfully rendered to image(s).");
    }
}

常见场景与解决问题

问题解决方案
Cut-off 内容使用 AllColumnsInOnePagePerSheet = true
产量质量低增强图像分辨率
迷失的线路设置 ShowGridLines = true
 中文