Come convertire un grafico di Excel in un'immagine in C#

Come convertire un grafico di Excel in un'immagine in C#

I grafici rappresentano visualmente i dati nei file Excel. Quando si condividono rapporti, si costruiscono dashboards o si genera la documentazione, potrebbe essere necessario esportare questi grafici ai file di immagine. Questo manuale mostra come convertire un grafico Excel in un’immagine utilizzando Aspose.Cells per .NET.

Perché trasformare le mappe in immagini?

  • Incorporare i dati visivi in siti web o presentazioni
  • Rapporti di posta elettronica senza bisogno di visualizzatori di Excel
  • Includere grafici in PDF o layout stampati

Guida passo dopo passo

Passo 1: Installare Aspose.Cells per .NET

dotnet add package Aspose.Cells

Passo 2: Carica il libro di lavoro

Workbook workbook = new Workbook("Dashboard.xlsx");
Worksheet sheet = workbook.Worksheets["Charts"];

Passo 3: Selezionare la scheda

// Access the first chart on the worksheet
Chart chart = sheet.Charts[0];

Passo 4: Impostare le opzioni di esportazione

ImageOrPrintOptions options = new ImageOrPrintOptions
{
    ImageType = ImageType.Png,
    HorizontalResolution = 300,
    VerticalResolution = 300,
    Transparent = false
};

Passo 5: Convertire il grafico in immagine

chart.ToImage("chart_output.png", options);

Passo 6: Salva e verifica

Questo salva il tuo grafico come file PNG. Puoi anche scegliere JPEG, BMP, TIFF, ecc.

Passo 7: Miglioramenti opzionali

È possibile controllare ulteriormente la dimensione e la qualità dell’immagine impostando:

// Control scaling
chart.ToImage("chart_highres.png", new ImageOrPrintOptions
{
    ImageType = ImageType.Jpeg,
    SmoothingMode = SmoothingMode.AntiAlias,
    ChartImageWidth = 1200,
    ChartImageHeight = 800
});

Codice esemplare completo

using System;
using Aspose.Cells;
using Aspose.Cells.Rendering;
using System.Drawing.Drawing2D;

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

        // Access the worksheet and first chart
        Worksheet sheet = workbook.Worksheets["Charts"];
        Chart chart = sheet.Charts[0];

        // Set image export options
        ImageOrPrintOptions options = new ImageOrPrintOptions
        {
            ImageType = ImageType.Png,
            HorizontalResolution = 300,
            VerticalResolution = 300,
            SmoothingMode = SmoothingMode.AntiAlias,
            ChartImageWidth = 1200,
            ChartImageHeight = 800
        };

        // Export chart to image
        chart.ToImage("chart_output.png", options);

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

Scenari e fissazioni comuni

Il problemaLa soluzione
Il grafico è blurryAumentare ChartImageWidth e ChartImageHeight
L’immagine manca di chiarezzaUtilizzo SmoothingMode = AntiAlias
Il grafico è tagliatoControlla i margini del foglio di lavoro o le impostazioni di scalazione
 Italiano