Create Excel Chart in Java

The following example shows how you can create an Excel chart in Java and select data for it using the GemBox.Spreadsheet for Java component.

Excel charts are supported only in XLSX.

To convert an existing workbook with charts into another file format, use Convert example.

For more information about charts, see the Charts help page.

Excel chart created with GemBox.Spreadsheet
Screenshot of Excel chart created with GemBox.Spreadsheet
import com.gembox.spreadsheet.*;
import com.gembox.spreadsheet.charts.*;

class Program {

    public static void main(String[] args) throws {
        // If using Professional version, put your serial key below.

        ExcelFile workbook = new ExcelFile();
        ExcelWorksheet worksheet = workbook.addWorksheet("Chart");

        int numberOfEmployees = %EmployeesCount%;

        // Create Excel chart and select data for it.
        ExcelChart chart = worksheet.getCharts().add(ChartType.BAR, "D2", "M25");
        chart.selectData(worksheet.getCells().getSubrangeAbsolute(0, 0, numberOfEmployees, 1), true);

        // Add data which is used by the Excel chart.
        String[] names = new String[] { "John Doe", "Fred Nurk", "Hans Meier", "Ivan Horvat" };
        java.util.Random random = new java.util.Random();
        for (int i = 0; i < numberOfEmployees; i++) {
            worksheet.getCell(i + 1, 0).setValue(names[i % names.length] + (i < names.length ? "" : " " + (i / names.length + 1)));
            worksheet.getCell(i + 1, 1).setValue(random.nextInt(4000) + 1000);

        // Set header row and formatting.
        worksheet.getCell(0, 0).setValue("Name");
        worksheet.getCell(0, 1).setValue("Salary");
        worksheet.getCell(0, 1).getStyle().getFont().setWeight(ExcelFont.BOLD_WEIGHT);
        worksheet.getCell(0, 0).getStyle().getFont().setWeight(ExcelFont.BOLD_WEIGHT);
        worksheet.getColumn(0).setWidth((int) LengthUnitConverter.convert(3, LengthUnit.CENTIMETER, LengthUnit.ZERO_CHARACTER_WIDTH_256_TH_PART));

Want more?

Next example GitHub

Check the next example or select an example from the menu. You can also download our examples from the GitHub.

Like it?

Download Buy

If you want to try the GemBox.Spreadsheet for Java yourself, you can download the free version. It delivers the same performance and set of features as the professional version, but with some operations limited. To remove the limitation, you need to purchase a license.