Como Converter uma Única Célula do Excel em Imagem em C#

Como Converter uma Única Célula do Excel em Imagem em C#

Às vezes tudo o que você precisa é um valor único – um preço, uma etiqueta, um código – e você quer exportar essa célula visualmente. este tutorial mostra como isolar e render uma única célula do Excel para uma imagem usando Aspose.Cells para .NET.

Casos de uso do mundo real

  • Preços de exportação ou total para exibições de produtos
  • Metricas de chave isoladas para dashboards
  • Gerar miniaturas de imagem para valores individuais

Guia passo a passo

Passo 1: Instalar Aspose.Cells para .NET

dotnet add package Aspose.Cells

Passo 2: Carregar o livro de trabalho e folheto de trabalho

Workbook workbook = new Workbook("KPIReport.xlsx");
Worksheet sheet = workbook.Worksheets[0];

Passo 3: Selecione a célula-alvo

// Example: Cell B5
Cell cell = sheet.Cells["B5"];

Passo 4: Configure a área de impressão para a célula

// Print only that one cell
sheet.PageSetup.PrintArea = "B5";

Passo 5: Configurar opções de renderização de imagem

ImageOrPrintOptions options = new ImageOrPrintOptions
{
    ImageType = ImageType.Png,
    OnePagePerSheet = true,
    HorizontalResolution = 300,
    VerticalResolution = 300
};

Passo 6: Render usando SheetRender

SheetRender renderer = new SheetRender(sheet, options);
renderer.ToImage(0, "cell_b5_output.png");

Passo 7: Salvar e revisar a saída

Você obterá um PNG limpo mostrando apenas que uma célula com formatação está intact.

Código de Exemplo Completo

using System;
using Aspose.Cells;

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

        // Access the worksheet and target cell
        Worksheet sheet = workbook.Worksheets[0];
        Cell cell = sheet.Cells["B5"];

        // Set print area to that cell
        sheet.PageSetup.PrintArea = "B5";

        // Image export settings
        ImageOrPrintOptions options = new ImageOrPrintOptions
        {
            ImageType = ImageType.Png,
            OnePagePerSheet = true,
            HorizontalResolution = 300,
            VerticalResolution = 300
        };

        // Render and save
        SheetRender renderer = new SheetRender(sheet, options);
        renderer.ToImage(0, "cell_b5_output.png");

        Console.WriteLine("Cell B5 exported successfully as image.");
    }
}

Sugestões úteis

TipoDescrição
Melhorar a leituraAumentar a resolução ou o tamanho da fonte
Adicionar fundo ou fronteiraFormato de célula antes da renderização
Conteúdo AlignUtilização cell.GetStyle() para alinhamento ou padding
 Português