DEV Community

CodeSharing
CodeSharing

Posted on

Java/ Split Contents in One Cell into Multiple Columns

When dealing with data in Excel documents, it may sometimes be necessary to split the information in one cell into mutiple columns so that each column can be processed separately in the next step. This article will introduce how to use Free Spire.XLS for Java (a 3rd party free API) to split the text or numbers in one Excel cell into multiple columns by delimiters. The delimiter characters could be Space, Comma, Semicolon, etc.

Installation
Method 1: Download the free API 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>
Enter fullscreen mode Exit fullscreen mode

Relevant Code Snippet

import com.spire.xls.*;

public class splitDataIntoMultipleColumns {
    public static void main(String[] args) {
        //Load the sample document from file
        Workbook workbook = new Workbook();
        workbook.loadFromFile("source data.xlsx");

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

        //Split data into separate columns by the delimiter characters of space.
        String[] splitText = null;
        String text = null;
        for (int i = 1; i < sheet.getLastRow(); i++)
        {
            text = sheet.getRange().get(i + 1, 1).getText();
            splitText = text.split(" ");
            for (int j = 0; j < splitText.length; j++)
            {
                sheet.getRange().get(i + 1, 1 + j + 1).setText(splitText[j]);
            }
        }
        //Save to file
        workbook.saveToFile("SplitCell.xlsx", ExcelVersion.Version2013);
    }
}
Enter fullscreen mode Exit fullscreen mode

Result
Alt Text

Top comments (0)