How to Convert an Excel Chart to Image in C#
How to Convert an Excel Chart to Image in C#
Charts visually represent data in Excel files. When sharing reports, building dashboards, or generating documentation, you might need to export those charts to image files. This guide shows how to convert an Excel chart to an image using Aspose.Cells for .NET.
Why Convert Charts to Images?
- Embed visual data in websites or presentations
- Email reports without needing Excel viewers
- Include charts in PDFs or print layouts
Step-by-Step Guide
Step 1: Install Aspose.Cells for .NET
dotnet add package Aspose.Cells
Step 2: Load the Workbook
Workbook workbook = new Workbook("Dashboard.xlsx");
Worksheet sheet = workbook.Worksheets["Charts"];
Step 3: Select the Chart
// Access the first chart on the worksheet
Chart chart = sheet.Charts[0];
Step 4: Set Export Options
ImageOrPrintOptions options = new ImageOrPrintOptions
{
ImageType = ImageType.Png,
HorizontalResolution = 300,
VerticalResolution = 300,
Transparent = false
};
Step 5: Convert Chart to Image
chart.ToImage("chart_output.png", options);
Step 6: Save and Verify
This saves your chart as a PNG file. You can also choose JPEG, BMP, TIFF, etc.
Step 7: Optional Enhancements
You can control image size and quality further by setting:
// Control scaling
chart.ToImage("chart_highres.png", new ImageOrPrintOptions
{
ImageType = ImageType.Jpeg,
SmoothingMode = SmoothingMode.AntiAlias,
ChartImageWidth = 1200,
ChartImageHeight = 800
});
Complete Example Code
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.");
}
}
Common Scenarios & Fixes
Issue | Solution |
---|---|
Chart appears blurry | Increase ChartImageWidth and ChartImageHeight |
Image lacks clarity | Use SmoothingMode = AntiAlias |
Chart is clipped | Check worksheet margins or scaling settings |