Wednesday, 5 January 2022

Wrap or Unwrap Text in Excel Cells using Java

In the process of manipulating Excel worksheets, sometimes you may encounter the situation that the text in a cell is so long that some of it is hidden. At this time, it’s recommended to wrap the extra-long text into multiple lines so you can see all of it. This article will demonstrate how to automatically wrap or unwrap text in Excel cells using Java codes.

DEPENDENCY

First of all, you’re required to get the package of a free third-party library called Free Spire.XLS for Java from the link, and then manually add Spire.Xls.jar to your project. Or if you use Maven, you can import the following code to the pom.xml file to add the JAR 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.free</artifactId>
<version>3.9.1</version>
</dependency>
</dependencies>

USING THE CODE

Free Spire.XLS for Java supports wrapping or unwrapping text in Excel cells using the setWrapText() method provided by the IExtendedFormat interface. Below are detailed steps for your reference.

l  Create a Workbook instance.

l  Load a sample Excel document using Workbook.loadFromFile() method.

l  Get a specific worksheet of the document using Workbook.getWorksheets().get() method.

l  Get a specific cell of the worksheet using Worksheet.getRange().get() method.

l  Get the style of the specified cell using XlsRange.getStyle() method and set whether the text is wrapped or not using setWrapText() method provided by the IExtendedFormat interface.

l  Save the document to another file using Workbook.saveToFile() method.

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

public class WrapOrUnwrapText {
public static void main(String[] args) {
//Create a Workbook instance
Workbook workbook = new Workbook();
//Load a sample Excel document
workbook.loadFromFile("C:\\Users\\Test1\\Desktop\\sample.xlsx");

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

//Wrap text in the cell "D8"
sheet.getRange().get("D8").getStyle().setWrapText(true);

//Unwrap text in the cell "D6"
sheet.getRange().get("D6").getStyle().setWrapText(false);

//Save the document to another file
workbook.saveToFile("output/WrapOrUnwrapText.xlsx", ExcelVersion.Version2013);
}
}





No comments:

Post a Comment

Change PDF Versions in Java

In daily work, you might need to change the version of a PDF document you have in order to ensure compatibility with another version which a...