Text box allows people to enter text in it and move it arbitrarily. 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 chart programmatically using Spire.XLS for Java.
Install Spire.XLS for Java
First of all, you're required to add the Spire.Xls.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.xls</artifactId> <version>14.11.0</version> </dependency> </dependencies>
Add a Text Box to a Chart
The detailed steps are listed as below.
- Create a Workbook instance and load a sample Excel document using Workbook.loadFromFile() method.
- Get a specified worksheet using Workbook.getWorksheets().get() method.
- Get a specific chart using Worksheet.getCharts().get() method.
- 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.
- Set the size and position of the added text box using the method offered by ITextBoxLinkShape interface.
- Save the document to file using Workbook.saveToFile() method.
- Java
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("DoughnutChart.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("Modified by Louis on September 06, 2021"); //Set the size and position of the text box textbox.setWidth(1100); textbox.setHeight(480); textbox.setLeft(2800); textbox.setTop(480); //Save the result file workbook.saveToFile("addTextBoxToChart.xlsx", ExcelVersion.Version2013); } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.