Create Excel Chart Sheet in Java
GemBox.Spreadsheet for Java has been retired
The following example shows how you can create an Excel chart sheet in Java and select data for it using the GemBox.Spreadsheet for Java component.
Excel chart sheets are supported only in XLSX
To convert an existing workbook with chart sheets into another file format, use Convert example.
For more information about chart sheets, see the Charts help page.

import com.gembox.spreadsheet.*;
import com.gembox.spreadsheet.charts.*;
class Program {
public static void main(String[] args) throws java.io.IOException {
// If using the Professional version, put your serial key below.
SpreadsheetInfo.setLicense("FREE-LIMITED-KEY");
ExcelFile workbook = new ExcelFile();
int numberOfEmployees = %EmployeesCount%;
ExcelWorksheet worksheet1 = workbook.addWorksheet("SourceSheet");
// 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++)
{
worksheet1.getCell(i + 1, 0).setValue(names[i % names.length] + (i < names.length ? "" : " " + (i / names.length + 1)));
worksheet1.getCell(i + 1, 1).setValue(random.nextInt(4000) + 1000);
}
// Set header row and formatting.
worksheet1.getCell(0, 0).setValue("Name");
worksheet1.getCell(0, 1).setValue("Salary");
worksheet1.getCell(0, 1).getStyle().getFont().setWeight(ExcelFont.BOLD_WEIGHT);
worksheet1.getCell(0, 0).getStyle().getFont().setWeight(ExcelFont.BOLD_WEIGHT);
worksheet1.getColumn(0).setWidth((int)LengthUnitConverter.convert(3, LengthUnit.CENTIMETER, LengthUnit.ZERO_CHARACTER_WIDTH_256_TH_PART));
worksheet1.getColumn(1).getStyle().setNumberFormat("\"$\"#,##0");
// Create Excel chart sheet.
ExcelWorksheet worksheet2 = workbook.getWorksheets().add(SheetType.CHART, "ChartSheet");
// Create Excel chart and select data for it.
// You cannot set the size of the chart area when the chart is located on a chart sheet, it will snap to maximum size on the chart sheet.
ExcelChart chart = worksheet2.getCharts().add(ChartType.BAR, 0, 0, 0, 0, LengthUnit.CENTIMETER);
chart.selectData(worksheet1.getCells().getSubrangeAbsolute(0, 0, numberOfEmployees, 1), true);
workbook.save("Chart Sheet.xlsx");
}
}
See also
Next steps
Published: December 13, 2018 | Modified: April 28, 2023 | Author: Marek Turis