Java/ Add a Text Box to a Chart in Excel

When dealing with the chart in Excel document, if the text description of the original chart is not specific enough, you can add additional information to the chart by adding text boxes to it. This article will introduce how to add a text box to a Excel chart programmatically using Free Spire.XLS for Java.

Install Free Spire.XLS for Java
Method 1: Download the free Java library and unzip it, then add the Spire.Xls.jar file to your project as dependency.

Method 2: You can also add the jar dependency to maven project by adding the following configurations to the pom.xml.

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.xls.free</artifactId>
<version>3.9.1</version>
</dependency>
</dependencies>

Sample Code

Free Spire.XLS for Java offers the Worksheet.getCharts().get() method to get a specific chart. After getting the chart, you can add a text box to the chart using Chart.getShapes().addTextBox() method, and then add text content in the text box using ITextBoxLinkShape.setText() method.

import com.spire.xls.*;
import com.spire.xls.core.*;

public class addTextBoxToChart {
public static void main(String[] args)throws Exception {
//Create a Workbook instance
Workbook workbook = new Workbook();

//Load an Excel document
workbook.loadFromFile("ScatterChart.xlsx");

//Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);

//Get the first chart
Chart chart = sheet.getCharts().get(0);

//Add a text box to the chart
ITextBoxLinkShape textbox = chart.getShapes().addTextBox();
textbox.setText("Data provided by Louis");

//Set the size and position of the text box
textbox.setWidth(800);
textbox.setHeight(480);
textbox.setLeft(3100);
textbox.setTop(400);

//Save the result file
workbook.saveToFile("addTextBoxToChart.xlsx", ExcelVersion.Version2013);
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store