Com convertir un full de llibre de treball d'Excel a una imatge en C#

Com convertir un full de llibre de treball d'Excel a una imatge en C#

El rendiment de fitxers d’Excel com a imatges és essencial quan s’incorporen tauletes en pàgines web, documentació o informes. Aquest article demostra com convertir un full de treball de Excel en formats d’imatge de qualitat utilitzant Aspose.Cells per a .NET.

Per què convertir llibres de treball en imatges?

  • Generació de previsions per a fitxers d’Excel
  • Arxiu en format d’imatges
  • Incorporar el contingut de la taula en informes o fluxos de treball d’impressió
  • Mostra tauletes en aplicacions que no suporten la visualització nativa d’Excel

Implementació de pas a pas

Pas 1: Instal·lar Aspose.Cells per a .NET

Afegeix Aspose.Cells al teu projecte utilitzant NuGet:

dotnet add package Aspose.Cells

Pas 2: Carregar el fitxer d’Excel

Workbook workbook = new Workbook("Book1.xlsx");

Pas 3: Configuració d’opcions d’imatge

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

Aquestes configuracions controlen el format de sortida i la resolució. També podeu configurar:

  • Transparent for background
  • OnlyArea to exclude margins
  • PrintingPageType for what content to include

Pas 4: Renderar el llibre de treball

WorkbookRender renderer = new WorkbookRender(workbook, options);

Pas 5: Convertir cada pàgina en imatge

Passar per les pàgines i exportar cadasc:

for (int i = 0; i < renderer.PageCount; i++)
{
    string fileName = $"workbook_page_{i + 1}.png";
    renderer.ToImage(i, fileName);
}

Això generarà una imatge per pàgina lògica basada en el disseny d’impressió actual.

Pas 6: Salvar les imatges

El codi anterior ja emmagatzema cada fitxer d’imatge al disc utilitzant el nom definit.

// Output:
// workbook_page_1.png
// workbook_page_2.png
// ...

Pas 7: millores opcionals

Podeu fer un altre rendiment d’imatge fin-tune:

// Example: show gridlines
options.ShowGridLines = true;

// Example: render the entire sheet content in one page
options.AllColumnsInOnePagePerSheet = true;

Les millors pràctiques

  • Utilitza alta resolució (200+ dpi) per a imatges de qualitat d’impressi.
  • Enable AllColumnsInOnePagePerSheet for wide sheets.
  • Combina la sortida en un PDF o galeria d’imatges per a presentacions.

Problemes i solucions comunes

qüestióSolució
La imatge de sortida és blancaAssegurar que el llibre de treball està carregat i conté dades visibles
La imatge es redueixSet OnePagePerSheet = true or adjust page scaling
Producció de baixa qualitatIncrease HorizontalResolution and VerticalResolution
 Català