Com convertir un gràfic d'Excel en imatge en C#
Com convertir un gràfic d'Excel en imatge en C#
Els gràfics representen visualment les dades en els fitxers d’Excel. Quan comparteixin informes, construeixin dashboards o generen documentació, pot ser que s’exportin aquells diagrams a arxius de la imatge. Aquest guia mostra com convertir una gràfica d’Excell a una imatge utilitzant Aspose.Cells per a .NET.
Per què es converteixen els gràfics en imatges?
- Integració de dades visuals en llocs web o presentacions
- Informes de correu electrònic sense necessitat de visualitzadors d’Excel
- Incloure gràfics en PDFs o dissenys d’impressió
Guia de pas a pas
Pas 1: Instal·lar Aspose.Cells per a .NET
dotnet add package Aspose.Cells
Pas 2: Carregar el llibre de treball
Workbook workbook = new Workbook("Dashboard.xlsx");
Worksheet sheet = workbook.Worksheets["Charts"];
Pas 3: Seleccioneu el mapa
// Access the first chart on the worksheet
Chart chart = sheet.Charts[0];
Pas 4: Definició de les opcions d’exportació
ImageOrPrintOptions options = new ImageOrPrintOptions
{
ImageType = ImageType.Png,
HorizontalResolution = 300,
VerticalResolution = 300,
Transparent = false
};
Pas 5: Convertir el quadre a la imatge
chart.ToImage("chart_output.png", options);
Pas 6: Conservar i comprovar
Això salva el teu gràfic com a fitxer PNG. També pots triar JPEG, BMP, TIFF, etc.
Pas 7: millores opcionals
Podeu controlar més la mida i la qualitat de la imatge mitjançant la configuraci:
// Control scaling
chart.ToImage("chart_highres.png", new ImageOrPrintOptions
{
ImageType = ImageType.Jpeg,
SmoothingMode = SmoothingMode.AntiAlias,
ChartImageWidth = 1200,
ChartImageHeight = 800
});
Codi d’exemple complet
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.");
}
}
Escenaris i fixos comuns
qüestió | Solució |
---|---|
El quadre apareix blurí | Increase ChartImageWidth and ChartImageHeight |
La imatge no té claredat | Use SmoothingMode = AntiAlias |
El mapa està clavegat | Consulteu les marges de la taula de treball o les configuracions d’escalació |