DEV Community

Cover image for Export Excel Charts as Images in Java: Single Charts, Multiple Charts, and Chart Sheets
Dheeraj Malik
Dheeraj Malik

Posted on Edited on

Export Excel Charts as Images in Java: Single Charts, Multiple Charts, and Chart Sheets

Charts in Excel are often useful beyond the workbook itself. You might want to add a sales chart to a presentation, include a trend line in a report, or display a chart on a web page. Taking screenshots works for the occasional chart, but it becomes tedious when a workbook contains several charts, and the results may require extra cropping.

With Java, you can export existing Excel charts directly as PNG images without recreating the charts or capturing the entire worksheet. This tutorial covers three cases: exporting a specific chart, saving every chart in a worksheet, and exporting a standalone chart sheet.

Set Up the Java Project

Add the following repository and dependency to your Maven project's pom.xml:

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>

<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.xls.free</artifactId>
        <version>16.3.1</version>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

If your pom.xml already contains <repositories> or <dependencies>, add the entries to the existing sections rather than creating duplicate top-level elements.

Prepare a Sample Excel Workbook

The examples use a workbook named sales_report.xlsx with the following sheets:

  • Sales Summary — a regular worksheet containing a quarterly sales column chart and a sales trend line chart.
  • Regional Sales — a regular worksheet with a pie chart showing sales by region.
  • Annual Sales Share — a standalone chart sheet, rather than a chart embedded in a cell-based worksheet.

Save sales_report.xlsx in the program's working directory. Each example loads the same workbook independently and creates its own output files.

1. Export a Specific Excel Chart as a PNG Image

If you need just one chart—say, the quarterly sales chart—you can select it by its index in the worksheet instead of exporting the entire sheet.

The Workbook.saveChartAsImage(Worksheet, int) method returns a BufferedImage for the specified chart. Chart indexes are zero-based, so 0 refers to the first chart in that worksheet. Java's ImageIO.write() can then save the returned image as a PNG file.

Complete Java code:

import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class ExportSingleExcelChart {

    public static void main(String[] args) throws IOException {
        Workbook workbook = new Workbook();

        try {
            workbook.loadFromFile("sales_report.xlsx");
            Worksheet sheet = workbook.getWorksheets().get(0);

            if (sheet.getCharts().getCount() == 0) {
                System.out.println("No charts found in the worksheet.");
                return;
            }

            // Export the first embedded chart
            BufferedImage image = workbook.saveChartAsImage(sheet, 0);

            Path outputDir = Paths.get("output/single_chart");
            Files.createDirectories(outputDir);

            ImageIO.write(image, "png",
                    outputDir.resolve("quarterly_sales.png").toFile());

            System.out.println("Chart exported.");
        } finally {
            workbook.dispose();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

The program saves the first chart as output/single_chart/quarterly_sales.png. To export another chart from the same worksheet, change the index to 1, 2, and so on, provided that the chart exists.

2. Export All Charts from an Excel Worksheet

A worksheet may contain several charts that you want to reuse in a report or dashboard. Instead of exporting them one by one, you can get them all in a single call.

Workbook.saveChartAsImage(Worksheet) returns a BufferedImage[] containing the images of the charts in that worksheet. The following program loops through the array and saves each image with a sequential filename.

Complete Java code:

import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class ExportAllExcelCharts {

    public static void main(String[] args) throws IOException {
        Workbook workbook = new Workbook();

        try {
            workbook.loadFromFile("sales_report.xlsx");
            Worksheet sheet = workbook.getWorksheets().get(0);

            if (sheet.getCharts().getCount() == 0) {
                System.out.println("No charts found in the worksheet.");
                return;
            }

            // Render every embedded chart in the worksheet
            BufferedImage[] images = workbook.saveChartAsImage(sheet);

            Path outputDir = Paths.get("output/all_charts");
            Files.createDirectories(outputDir);

            for (int i = 0; i < images.length; i++) {
                Path outputFile = outputDir.resolve("chart_" + (i + 1) + ".png");
                ImageIO.write(images[i], "png", outputFile.toFile());
            }

            System.out.println("Exported " + images.length + " charts.");
        } finally {
            workbook.dispose();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

If the first worksheet contains two charts, the output folder will look like this:

output/
└── all_charts/
    ├── chart_1.png
    └── chart_2.png
Enter fullscreen mode Exit fullscreen mode

This method handles charts on the selected worksheet only. If your charts are distributed across several worksheets, iterate over the worksheets and export each sheet's charts separately.

3. Export an Excel Chart Sheet as an Image

Excel also supports chart sheets, where a chart occupies its own sheet instead of appearing within a regular worksheet. These are different from embedded charts, so they use a different overload.

You can access a chart sheet through Workbook.getChartsheets() and pass it to Workbook.saveChartAsImage(ChartSheet). The following example exports the first chart sheet to PNG. Notice the explicit cast: the Java API documents getChartsheets() as returning a raw ArrayList.

Complete Java code:

import com.spire.xls.Workbook;
import com.spire.xls.ChartSheet;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class ExportExcelChartSheet {

    public static void main(String[] args) throws IOException {
        Workbook workbook = new Workbook();

        try {
            workbook.loadFromFile("sales_report.xlsx");

            if (workbook.getChartsheets().isEmpty()) {
                System.out.println("No chart sheets found in the workbook.");
                return;
            }

            // Access the first standalone chart sheet
            ChartSheet chartSheet = (ChartSheet) workbook.getChartsheets().get(0);
            BufferedImage image = workbook.saveChartAsImage(chartSheet);

            Path outputDir = Paths.get("output/chart_sheet");
            Files.createDirectories(outputDir);

            ImageIO.write(image, "png",
                    outputDir.resolve("annual_sales_share.png").toFile());

            System.out.println("Chart sheet exported.");
        } finally {
            workbook.dispose();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

The exported image is saved as output/chart_sheet/annual_sales_share.png. If a workbook contains several chart sheets, you can select the one you need rather than assuming the first is always the right one.

Common Questions

1. What is the difference between exporting a chart and exporting a worksheet?

saveChartAsImage() exports the chart itself. It does not include the surrounding cell grid or values outside the chart. If you need an image of the entire worksheet, use a worksheet-to-image method such as Worksheet.saveToImage() instead.

2. Why doesn't the program find my chart?

First, check whether the object in Excel is an actual chart or just a pasted picture. Then confirm that the code targets the worksheet containing that chart. A standalone chart sheet is handled separately and won't appear in the ordinary worksheet's embedded-chart collection.

3. Can I edit the exported chart in Excel?

The PNG is a static image: you cannot change its data series or axes as you would in Excel. Exporting does not modify the original chart in the workbook, however, so you can edit the original and generate a new image whenever the data changes.

4. Why does the exported chart look slightly different from Excel?

Chart images are rendered outside Excel, so font availability and support for particular chart features can affect the output. This is especially noticeable when a workbook uses custom fonts or complex chart types. Check a representative image before exporting a large batch.

5. Can I export charts as JPEG instead of PNG?

You can use Java's ImageIO to write a JPEG, but JPEG does not support transparency. If the rendered image has an alpha channel, convert it to an RGB image first. For charts with labels, gridlines, and fine lines, PNG is usually a better default because it avoids JPEG compression artifacts.

Conclusion

If you already have charts in an Excel workbook, exporting them as images is often easier than recreating them or taking screenshots. Use the chart index when you need one chart, the worksheet overload to export all embedded charts, or the chart-sheet overload for a standalone chart sheet. The resulting PNG files can then be reused in presentations, reports, and web pages.

Top comments (0)