Cells

Cells (23)

Inserting Subscript in Excel using Java

Inserting subscript in Excel is a common requirement, especially when dealing with chemical formulas like CO₂, statistical footnotes, or scientific data. Using subscripts helps make data clearer and more polished, enhancing the professionalism of your documents. However, Excel’s built-in subscript feature is cumbersome and doesn’t support batch application, which can significantly slow down your workflow.

Fortunately, with the help of Java code, you can efficiently insert subscripts in Excel, freeing yourself from tedious manual work and making your tasks faster and more professional.

Preparation

Inserting a subscript in Excel using Java involves adding Java libraries. In today’s blog, we will use Spire.XLS for Java as an example to accomplish this task. Spire.XLS is a powerful Java component that works independently without relying on Microsoft Office. In addition to reading, editing, and converting Excel files, it allows users to perform advanced tasks as well.

To install it on your device, there are two options:

  1. If you are using Maven, add the following code to your 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>15.10.5</version>
    </dependency>
</dependencies>

  1. If you prefer manual installation, download the Spire.XLS package and add the .jar file to your Java IDE.

Inserting Subscript in Excel: How to Insert New Text with Subscript

First, let’s see how to insert new text into an Excel cell with subscript formatting already applied. By setting the subscript when creating a new document, you can generate the final file directly without needing to reopen and adjust it later.

Steps—Inserting subscript in Excel when adding new text with Java:

  • Create a Workbook and get a worksheet.
  • Get a cell range using Worksheet.getCellRange() method.
  • Specify text through CellRange.getRichText().setText() method.
  • Create a font through Workbook.createFont() method.
  • Set ExcelFont.isSubscript() to true.
  • Apply the font to a text range in the cell using RichText.setFont(startIndex, endIndex, font) method.

The following code shows how to insert the text "R100-0.06" into cell B2 and set the subscript:

import com.spire.xls.*;  
  
import java.awt.*;  
  
public class InsertSubscriptNewText {  
  
    public static void main(String[] args) {  
  
        // Create a Workbook instance  
        Workbook workbook = new Workbook();  
  
        // Get the first worksheet  
        Worksheet sheet = workbook.getWorksheets().get(0);  
  
        // Insert text to B2  
        sheet.getCellRange("B2").setText("This is an example of Subscript:");  
  
        // Insert text to B3 and apply subscript effect  
        CellRange range = sheet.getCellRange("B3");  
        range.getRichText().setText("R100-0.06");  
        ExcelFont font = workbook.createFont();  
        font.isSubscript(true);  
        font.setColor(Color.red);  
        range.getRichText().setFont(4, 8, font);  
  
        // Auto fit column width  
        sheet.getAllocatedRange().autoFitColumns();  
  
        // Save the document  
        workbook.saveToFile("/SubscriptNewText.xlsx", ExcelVersion.Version2016);  
    }  
}

Result Preview:

Inserting Subscript in Excel with New Text Using Java

Tip: By setting ExcelFont.isSuperscript() to true, you can apply superscript to text in Excel files.

Inserting Subscript in Excel: Apply Subscript to Existing Text

Although inserting subscripts while creating a new Excel file can simplify later work, in most cases, you’ll need to deal with existing files that already contain content. This section shows you how to quickly apply subscript formatting to existing text in Excel using Java.

Steps—Inserting subscript to Excel file with existing text:

  • Create a Workbook instance and read an Excel file.
  • Get a worksheet and get the cell range.
  • Loop through cells in the cell range and find the text to apply subscript.
  • Set the text in the cell’s rich text using RichText.setText() to preserve the existing content.
  • Create a font by calling Workbook.createFont() method and configure it as Subscript by setting ExcelFont.isSubscript() to true.
  • Apply the subscript using RichText.setFont(index, index, subFont) method.

The following code demonstrates how to set subscripts for chemical formulas in the cells within the A1:A3 range:

import com.spire.xls.*;  
  
public class SubscriptExistingContent {  
  
    public static void main(String[] args) {  
        // Create a Workbook and load an Excel file  
        Workbook workbook = new Workbook();  
        // Load an Excel file  
        workbook.loadFromFile(("/test.xlsx"));  
  
        // Get a worksheet  
        Worksheet sheet = workbook.getWorksheets().get(0);  
  
        // Loop through A1:A3  
        for (int i = 1; i <= 3; i++) {  
            CellRange cell = sheet.getCellRange("A" + i);  
            String text = cell.getText();  
  
            // Find "2" in cells  
            int index = text.indexOf("2");  
            if (index != -1) {  
                // Set RichText to keep original text   
cell.getRichText().setText(text);  
  
                // Create font and set as subscript  
                ExcelFont subFont = workbook.createFont();  
                subFont.isSubscript(true);  
  
                // Apply subscript to "2"  
                cell.getRichText().setFont(index, index, subFont);  
            }  
        }  
  
        // Auto fit columns  
        sheet.getAllocatedRange().autoFitColumns();  
  
        // Save the Excel file  
        workbook.saveToFile("/SubscriptExistingContent.xlsx", ExcelVersion.Version2016);  
    }  
}  

Result Preview:

Apply Subscript to Existing Text in Excel Using Java

The above code helps us find and set the first matching character as a subscript in an existing cell. But what if the same character appears multiple times in the same cell? How can we apply subscripts to all of them at once? Let’s explore this in the next section.

Inserting Subscript in Excel: Handle Multiple Matches in a Single Cell

Using a search-and-apply method to set subscript formatting works well when there is only one instance in the cell that needs to be subscripted, such as in H₂. However, if the cell contains a chemical equation, the situation becomes more complex: there might be multiple places where subscripts are needed, along with normal numbers representing coefficients (e.g., 2H₂ + O₂ → 2H₂O). In this case, the solution is to set subscripts precisely by specifying the exact positions of the target characters in the text. Let’s take a look at the detailed steps.

Steps—Inserting multiple subscripts in Excel cells:

  • Create a Workbook object and read an Excel file.
  • Get a worksheet and a cell range.
  • Read text in the cell range and set it to rich text using CellRange.getRichText().setText() method.
  • Create a font by calling Workbook.createFont() method and configure it as subscript by setting ExcelFont.isSubscript() to true.
  • Apply subscript to specific characters with CellRange.getRichText().setFont(index, index, subFont) method.

The following code demonstrates how to set subscripts for the necessary parts of the chemical equation “2H₂ + O₂ → 2H₂O” in cell C2:

import com.spire.xls.*;  
  
public class SubscriptSpecificCell {  
  
    public static void main(String[] args) {  
        // Create a Workbook instance and load an Excel file  
        Workbook workbook = new Workbook();  
        workbook.loadFromFile(("/test.xlsx"));  
  
        // Get the first worksheet  
        Worksheet sheet = workbook.getWorksheets().get(0);  
  
        // Get a cell range  
        CellRange cell = sheet.getCellRange("C2");  
  
        // Read text from C2  
        String text = cell.getText();  
  
  
        // Set text to RichText  
        cell.getRichText().setText(text);  
  
        // Create font object and set it as subscript  
        ExcelFont subFont = workbook.createFont();  
        subFont.isSubscript(true);  
  
        // Set subscript for specific cell  
        cell.getRichText().setFont(2, 2, subFont);  
        cell.getRichText().setFont(7, 7, subFont);  
        cell.getRichText().setFont(13, 13, subFont);  
  
        // Auto fit columns  
        sheet.getAllocatedRange().autoFitColumns();  
          
        // Save the Excel file  
        workbook.saveToFile("/SubscriptSpecificCell.xlsx", ExcelVersion.Version2016);  
    }  
}

Result Preview:

Apply Subscript to Multiple Text in Excel Using Java

Conclusion

This guide provides a detailed explanation of how to set subscripts in Excel, whether you need to apply them to a single cell or a range of cells, and whether you’re formatting one instance or multiple occurrences. By the end of this page, inserting subscript in Excel will be a breeze for you. Give Spire.XLS a try and start creating professional Excel workbooks today!

In Excel, copying rows, columns, and cells is a fundamental operation that allows users to replicate data efficiently across different parts of a worksheet or between multiple worksheets. Understanding how to programmatically copy rows, columns, and cells in Excel can significantly streamline your data manipulation tasks, especially when working with large datasets or automating repetitive tasks. In this article, you will learn how to copy rows, columns and cells in Excel with formatting in Java 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>15.10.5</version>
    </dependency>
</dependencies>

Copy Rows in Excel with Formatting in Java

The Worksheet.copyRow(CellRange sourceRow, Worksheet destSheet, int destRowIndex, EnumSet<CopyRangeOptions> copyOptions) method in Spire.XLS for Java is used to duplicate rows either within the same worksheet or across different worksheets. The CopyRangeOptions parameter in this method gives developers the ability to control what aspects of the row are copied, such as all flags, conditional formatting, data validations, or just the formula values.

The following steps demonstrate how to copy rows with formatting between different worksheets using Spire.XLS for Java.

  • Create an object of the Workbook class.
  • Load an Excel file using the Workbook.loadFromFile() method.
  • Get the source worksheet and the destination worksheet using the Workbook.getWorksheets().get(index) method.
  • Get the desired row that you want to copy using the Worksheet.getRows()[index] method.
  • Copy the row and its formatting from the source worksheet to the destination worksheet using the Worksheet.copyRow(CellRange sourceRow, Worksheet destSheet, int destRowIndex, EnumSet<CopyRangeOptions> copyOptions) method.
  • Copy the column widths of cells in the source row to the corresponding cells in the destination row.
  • Save the workbook to a file using the Workbook.saveToFile() method.
  • Java
import com.spire.xls.*;

import java.util.EnumSet;

public class CopyRows {
    public static void main(String[] args) {
        // Create a Workbook object
        Workbook workbook = new Workbook();
        // Load an Excel file
        workbook.loadFromFile("ContactList.xlsx");

        // Get the source worksheet
        Worksheet sheet1 = workbook.getWorksheets().get(0);

        // Get the destination worksheet
        Worksheet sheet2 = workbook.getWorksheets().get(1);

        // Get the desired row that you want to copy
        CellRange row = sheet1.getRows()[0];

        // Copy the row from the source worksheet to the first row of the destination worksheet
        sheet1.copyRow(row, sheet2, 1, EnumSet.of(CopyRangeOptions.All));

        int columns = sheet1.getColumns().length;

        // Copy the column widths of the cells in the source row to the corresponding cells in the destination row
        for (int i = 0; i < columns; i++)
        {
            double columnWidth = row.getColumns()[i].getColumnWidth();
            sheet2.getRows()[0].getColumns()[i].setColumnWidth(columnWidth);
        }

        // Save the workbook to a file
        workbook.saveToFile("CopyRow.xlsx", ExcelVersion.Version2016);
        workbook.dispose();
    }
}

Copy Rows in Excel with Formatting in Java

Copy Columns in Excel with Formatting in Java

To copy columns in Excel while preserving their formatting, use the Worksheet.copyColumn(CellRange sourceColumn, Worksheet destSheet, int destColIndex, EnumSet<CopyRangeOptions> copyOptions) method. The detailed steps are outlined below.

  • Create an object of the Workbook class.
  • Load an Excel file using the Workbook.loadFromFile() method.
  • Get the source worksheet and the destination worksheet using the Workbook.getWorksheets().get(index) method.
  • Get the desired column that you want to copy using the Worksheet.getColumns()[index] method.
  • Copy the column and its formatting from the source worksheet to the destination worksheet using the Worksheet.copyColumn(CellRange sourceColumn, Worksheet destSheet, int destColIndex, EnumSet<CopyRangeOptions> copyOptions) method.
  • Copy the row heights of cells in the source column to the corresponding cells in the destination column.
  • Save the workbook to a file using the Workbook.saveToFile() method.
  • Java
import com.spire.xls.*;

import java.util.EnumSet;

public class CopyColumns {
    public static void main(String[] args) {
        // Create a Workbook object
        Workbook workbook = new Workbook();
        // Load an Excel file
        workbook.loadFromFile("ContactList.xlsx");

        // Get the source worksheet
        Worksheet sheet1 = workbook.getWorksheets().get(0);

        // Get the destination worksheet
        Worksheet sheet2 = workbook.getWorksheets().get(1);

        // Get the desired column that you want to copy
        CellRange column = sheet1.getColumns()[0];

        // Copy the column from the source worksheet to the first column of the destination worksheet
        sheet1.copyColumn(column, sheet2, 1, EnumSet.of(CopyRangeOptions.All));

        int rows = column.getRows().length;

        // Copy the row heights of cells in the source column to the corresponding cells in the destination column
        for (int i = 0; i < rows; i++)
        {
            double rowHeight = column.getRows()[i].getRowHeight();
            sheet2.getColumns()[0].getRows()[i].setRowHeight(rowHeight);
        }

        // Save the workbook to a file
        workbook.saveToFile("CopyColumn.xlsx", ExcelVersion.Version2016);
        workbook.dispose();
    }
}

Copy Columns in Excel with Formatting in Java

Copy Cells in Excel with Formatting in Java

Spire.XLS for Java also allows developers to copy cell ranges with formatting using the CellRange.copy(CellRange destRange, EnumSet<CopyRangeOptions> copyOptions) method. The detailed steps are provided below.

  • Create an object of the Workbook class.
  • Load an Excel file using the Workbook.loadFromFile() method.
  • Get the source worksheet and the destination worksheet using the Workbook.getWorksheets().get(index) method.
  • Get the source cell range and the destination cell range using the Worksheet.getCellRange() method.
  • Copy the source cell range and its formatting from the source worksheet to the destination cell range in the destination worksheet using the CellRange.copy(CellRange destRange, EnumSet<CopyRangeOptions> copyOptions) method.
  • Copy the row heights and column widths of the source cell range to the destination cell range.
  • Save the workbook to a file using the Workbook.saveToFile() method.
  • Java
import com.spire.xls.*;

import java.util.EnumSet;

public class CopyCells {
    public static void main(String[] args) {
        // Create a Workbook object
        Workbook workbook = new Workbook();
        // Load an Excel file
        workbook.loadFromFile("ContactList.xlsx");

        // Get the source worksheet
        Worksheet sheet1 = workbook.getWorksheets().get(0);

        // Get the destination worksheet
        Worksheet sheet2 = workbook.getWorksheets().get(1);

        // Get the source cell range
        CellRange range1 = sheet1.getCellRange("A1:E7");
        // Get the destination cell range
        CellRange range2 = sheet2.getCellRange("A1:E7");

        // Copy the source cell range from the source worksheet to the destination cell range in the destination worksheet
        range1.copy(range2, EnumSet.of(CopyRangeOptions.All));

        // Copy the row heights and column widths of the source cell range to the destination cell range
        for (int i = 0; i < range1.getRows().length; i++)
        {
            CellRange row = range1.getRows()[i];
        for (int j = 0; j < row.getColumns().length; j++)
            {
              CellRange column = row.getColumns()[j];
              range2.getRows()[i].getColumns()[j].setColumnWidth(column.getColumnWidth());
              range2.getRows()[i].setRowHeight(row.getRowHeight());
            }
        }

        // Save the workbook to a file
        workbook.saveToFile("CopyCells.xlsx", ExcelVersion.Version2016);
        workbook.dispose();
    }
}

Copy Cells in Excel with Formatting in Java

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.

Java: Create a Drop-Down List in Excel

2022-11-07 02:08:45 Written by Koohji

The drop-down list in Excel enables users to select a desired item from a pre-defined list of items as input data. It restricts the input of unwanted or ambiguous data and reduces the occurrence of spelling errors, which is a great option for speeding up data entry tasks. In this article, you will learn how to programmatically create a drop-down list in Excel 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>15.10.5</version>
    </dependency>
</dependencies>

Create a Drop-Down List Based on Values in a Cell Range

With Spire.XLS for Java, you can add values to a range of cells and then refer to that range of cells as the data validation source to create a drop-down list. This method might be slightly time-consuming, but it allows you to easily update the items in the drop-down list by directly modifying the values in the cells of the result document. The detailed steps are as follows.

  • Create a Workbook object.
  • Load a sample Excel document using Workbook.loadFromFile() method.
  • Get a specified worksheet using Workbook.getWorksheets().get() method.
  • Get a specified cell or cell range using Worksheet.getCellRange() method.
  • Add values to specified cells using CellRange.setValue() method.
  • Get data validation of the specified cell range using CellRange.getDataValidation() method.
  • Create a drop-down list by referring to a specified data range as the data validation source using Validation.setDataRange() method.
  • Save the result document using Workbook.saveToFile() method.
  • Java
import com.spire.xls.*;

public class DropdownList {
    public static void main(String[] args) {

        //Create a Workbook object
        Workbook workbook = new Workbook();

        //Load a sample Excel document
        workbook.loadFromFile("input.xlsx");

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

        //Add values to specified cells
        sheet.getCellRange("A13").setValue("Complete");
        sheet.getCellRange("A14").setValue("Pending");
        sheet.getCellRange("A15").setValue("Cancelled");

        //Create a drop-down list by referring to a specified data range as the data validation source
        sheet.getCellRange("C2:C7").getDataValidation().setDataRange(sheet.getCellRange("A13:A15"));

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

Java: Create a Drop-Down List in Excel

Create a Drop-Down List Based on Values in a String Array

In Excel, you can create a drop-down list by manually entering a list of values in the “Source” box of the Data Validation menu. By doing this, you don't need to add data in Excel cells, which keeps your Excel document neat and organized. The following steps shows how to use Spire.XLS for Java to achieve the same functionality.

  • Create a Workbook object.
  • Get a specified worksheet using Workbook.getWorksheets().get() method.
  • Add text to a cell and set its font style.
  • Get a specified cell or cell range using Worksheet.getCellRange() method.
  • Get data validation of the specified cell range using CellRange.getDataValidation() method.
  • Set the values of the drop-down list using Validation.setValues() method.
  • Create a drop-down list in the specified cell by setting the values of Validation.isSuppressDropDownArrow() method to false.
  • Save the result document using Workbook.saveToFile() method.
  • Java
import com.spire.xls.*;

public class DropdownList2 {
    public static void main(String[] args) {

        //Create a Workbook object
        Workbook workbook = new Workbook();

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

        //Add text to cell B2 and set its font style
        sheet.getCellRange("B2").setValue("Country");
        sheet.getCellRange("B2").getStyle().getFont().isBold(true);
        sheet.getCellRange("B2").getStyle().setKnownColor(ExcelColors.LightTurquoise);

        //Set the values of the drop-down list
        sheet.getCellRange("C2").getDataValidation().setValues(new String[]{"France", "Japan", "Canada", "China", "Germany"});

        //Create a drop-down list in the specified cell
        sheet.getCellRange("C2").getDataValidation().isSuppressDropDownArrow(false);

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

Java: Create a Drop-Down List in Excel

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.

AutoFit is a very practical feature MS Excel offers to automatically resize cells to accommodate different sized data. With a single click, it makes all the data in a cell clearly visible without having to manually adjust the column width or row height. In this article, you will learn how to programmatically AutoFit the column width and row height in an Excel worksheet using Spire.XLS for Java.

Install Spire.XLS for Java

First, 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>15.10.5</version>
    </dependency>
</dependencies>

AutoFit Column Width and Row Height in Excel

The detailed steps are as follows.

  • Create a Workbook object.
  • Load a sample Excel document using Workbook.loadFromFile() method.
  • Get a specified worksheet using Workbook.getWorksheets().get() method.
  • Get the used range on the specified worksheet using Worksheet.getAllocatedRange() method.
  • Autofit column width and row height in the range using CellRange.autoFitColumns() and CellRange.autoFitRows() methods.
  • Save the document to another file using Workbook.saveToFile() method.
  • Java
import com.spire.xls.*;

public class AutoFitColumn {
    public static void main(String[] args) {
        //Create a Workbook object
        Workbook workbook = new Workbook();

        //Load a sample Excel document
        workbook.loadFromFile("E:\\Files\\Test.xlsx");

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

        //AutoFit column width and row height
        worksheet.getAllocatedRange().autoFitColumns();
        worksheet.getAllocatedRange().autoFitRows();

        //Save the document
        workbook.saveToFile("AutoFitCell.xlsx", ExcelVersion.Version2013);
    }
}

Java: AutoFit Column Width and Row Height in Excel

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.

When working with an Excel document that contains a lot of data, setting color or pattern for selected cells can make it very easy for users to locate specific types of information. In Microsoft Excel, you can achieve this function by simply clicking the "Fill Color" button on the formatting toolbar. In this article, you will learn how to programmatically set background color and pattern style for a specified cell or cell range in Excel using Spire.XLS for Java.

Install Spire.XLS for Java

First, 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>15.10.5</version>
    </dependency>
</dependencies>

Set Background Color and Pattern for Excel Cells

The detailed steps are as follows.

  • Create a Workbook object.
  • Load a sample Excel document using Workbook.loadFromFile() method.
  • Get a specified worksheet using Workbook.getWorksheets().get() method.
  • Get a specified cell range using Worksheet.getRange().get() method.
  • Set background color for the specified cell range using CellRange.getStyle().setColor() method.
  • Set fill pattern style for the specified cell range using CellRange.getStyle().setFillPattern() method.
  • Save the result to another file using Workbook.saveToFile() method.
  • Java
import com.spire.xls.*;
import java.awt.*;

public class CellBackground {
    public static void main(String[] args) {
        //Create a Workbook object
        Workbook workbook = new Workbook();

        //Load a sample Excel document
        workbook.loadFromFile("C:\\Users\\Administrator\\Desktop\\data.xlsx");

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

        //Set background color for range "A1:E1" and "A2:A10"
        worksheet.getRange().get("A1:E1").getStyle().setColor(Color.green);
        worksheet.getRange().get("A2:A10").getStyle().setColor(Color.yellow);

        //Set background color for cell E8
        worksheet.getRange().get("E8").getStyle().setColor(Color.red);

        //Set fill pattern style for range "C4:D5"
        worksheet.getRange().get("C4:D5").getStyle().setFillPattern(ExcelPatternType.Percent25Gray);

        //Save the document
        workbook.saveToFile("CellBackground.xlsx", ExcelVersion.Version2013);
    }
}

Java: Set Background Color and Pattern for Excel Cells

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.

Sometimes we need to hide some rows and columns in Excel worksheets so that the data appears completely on one screen. At other times, we need to show all the hidden rows and columns to view the data completely. In this article, you will learn how to hide and show rows or columns in Excel in Java applications from the following four parts.

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>15.10.5</version>
    </dependency>
</dependencies>

Hide Rows and Columns

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.
  • Hide a specific column using Worksheet.hideColumn(int columnIndex)method.
  • Hide a specific row using Worksheet.hideRow(int rowIndex) method.
  • Save the document to file using Workbook.saveToFile() method.
  • Java
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;


public class HideRowsColumns {
    public static void main(String[] args) throws Exception {

        //Load the sample document
        Workbook wb = new Workbook();
        wb.loadFromFile("Sample.xlsx ");

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

        //Hide the third column
        sheet.hideColumn(3);

        //Hide the third row
        sheet.hideRow(3);

        //Save the document
        wb.saveToFile("HideRowsColumns.xlsx", ExcelVersion.Version2016);
    }
}

Java: Hide or Show Rows or Columns in Excel

Show Hidden Rows and Columns

  • Create a Workbook instance and load a sample Excel document using Workbook.loadFromFile() method.
  • Get a specified worksheet using Workbook.getWorksheets().get() method.
  • Show a hidden column using Worksheet.showColumn(int columnIndex)method.
  • Show a hidden row using Worksheet.showRow(int rowIndex) method.
  • Save the document to file using Workbook.saveToFile() method.
  • Java
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;


public class ShowRowsColumns {
    public static void main(String[] args) throws Exception {

        //Load the sample document
        Workbook wb = new Workbook();
        wb.loadFromFile("HideRowsColumns.xlsx ");

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

        //Unhide the third column
        sheet.showColumn(3);

        //Unhide the third row
        sheet.showRow(3);

        //Save the document
        wb.saveToFile("ShowRowsColumns.xlsx", ExcelVersion.Version2016);
    }
}

Java: Hide or Show Rows or Columns in Excel

Hide Multiple Rows and Columns

  • Create a Workbook instance and load a sample Excel document using Workbook.loadFromFile() method.
  • Get a specified worksheet using Workbook.getWorksheets().get() method.
  • Hide multiple columns using Worksheet.hideColumns(int columnIndex, int columnCount)method.
  • Hide multiple rows using worksheet.hideRows(int rowIndex, int rowCount) method.
  • Save the document to file using Workbook.saveToFile() method.
  • Java
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;


public class HideMultiRowsColumns {
    public static void main(String[] args) throws Exception {

        //Load the sample document
        Workbook wb = new Workbook();
        wb.loadFromFile("Sample01.xlsx ");

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

        //Hide multiple columns
        sheet.hideColumns(2,2);

        //Hide multiple rows
        sheet.hideRows(3,3);

        //Save the document
        wb.saveToFile("HideMultiRowsColumns.xlsx", ExcelVersion.Version2016);
    }
}

Java: Hide or Show Rows or Columns in Excel

Show Multiple Rows and Columns

  • Create a Workbook instance and load a sample Excel document using Workbook.loadFromFile() method.
  • Get a specified worksheet using Workbook.getWorksheets().get() method.
  • Loop through the rows and find the hidden rows using Worksheet.getRowIsHide() method.
  • Show all hidden rows using Worksheet.showRow(i) method.
  • Save the document to file using Workbook.saveToFile() method.
  • Java
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;


public class ShowMultiRowsColumns {
    public static void main(String[] args) throws Exception {

        //Load the sample document
        Workbook wb = new Workbook();
        wb.loadFromFile("HideMultiRowsColumns.xlsx");

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

        //Traverse all the rows 
        for (int i = 1; i <= sheet.getLastRow(); i++) {

                //detect if the row is hidden
                if (sheet.getRowIsHide(i)) {

                    //Show the hidden rows
                    sheet.showRow(i);
                }
            }

        //Traverse the columns and show all the hidden columns
        for (int j = 1; j <= sheet.getLastColumn(); j++) {
            if (sheet.getColumnIsHide(j)) {
                sheet.showColumn(j);
            }

            //Save the document
            wb.saveToFile("ShowMultiRowsColumns.xlsx", ExcelVersion.Version2016);
        }
    }
}

Java: Hide or Show Rows or Columns in Excel

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.

When working with Excel, you may sometimes need to find the common values between two ranges of cells in a worksheet. For this reason, it’s recommended that Java codes can be used to automatically find the intersection of certain ranges. In this article, you'll learn how to achieve the operation 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>15.10.5</version>
    </dependency>
</dependencies>

Get the Intersection of Two Cell Ranges in Excel

The following are detailed steps to get the intersection of two cell ranges in an Excel worksheet.

  • Create a Workbook instance and load a sample Excel file using Workbook.loadFromFile() method.
  • Get a specific worksheet of the file using Workbook.getWorksheets().get() method.
  • Specify two ranges of cells using Worksheet.getRange().get() method and get their intersection using XlsRange.intersect() method.
  • Create a StringBuilder instance.
  • Loop through the intersection and obtain cell values using CellRange.getValue() method.
  • Append the result to the StringBuilder instance using StringBuilder.append() method.
  • Java
import com.spire.xls.*;

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

        //Load a sample Excel file
        workbook.loadFromFile( "C:\\Users\\Test1\\Desktop\\sample.xlsx");

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

        //Specify two cell ranges and get their intersection
        CellRange range = sheet.getRange().get("B2:E7").intersect(sheet.getRange().get("C3:D7"));

        //Create a StringBuilder instance
        StringBuilder content = new StringBuilder();
        content.append("The intersection of the two ranges \"B2:E7\" and \"C3:D7\" is:"+"\n");

        //Loop through the intersection and obtain cell values
        for(CellRange r : range.getCellList())
        {
            content.append(r.getValue()+"\n");
        }

        //Output the result
        System.out.println(content);
    }
}

The input Excel:

Java: Get the Intersection of Two Cell Ranges in Excel

The output result:

Java: Get the Intersection of Two Cell Ranges in Excel

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.

To extract values from an Excel document, you can copy and paste cell data. Alternatively, you can obtain it automatically by utilizing Java code, which will not only save time and improve efficiency, but ensure there will be no errors. In this tutorial, you will learn how to extract the value of a specified cell by its name 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>15.10.5</version>
    </dependency>
</dependencies>

Get Cell Values by Cell Names in Excel

Spire.XLS for Java offers Worksheet.getRange().get() method to specify a cell in Excel by its name, and CellRange.getValue() method to obtain the cell value. The detailed steps are listed as below.

  • Create a Workbook instance.
  • Load an Excel sample document using Workbook.loadFromFile() method.
  • Get a specified worksheet using Workbook.getWorksheets().get() method.
  • Get a specific cell by its name using Worksheet.getRange().get() method.
  • Create a StringBulider instance.
  • Obtain the cell value using CellRange.getValue() method, and then append the value to the StringBuilder instance using StringBuilder.append() method.
  • Java
import com.spire.xls.*;

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

        //Load an Excel sample document
        workbook.loadFromFile( "C:\\Users\\Test1\\Desktop\\sample.xlsx");

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

        //Get the specified cell by its name
        CellRange cell = sheet.getRange().get("D6");
       
        //Create a StringBuilder instance
        StringBuilder content = new StringBuilder();

        //Get value of the cell "D6" 
        content.append("The value of cell D6 is: " + cell.getValue()+"\n");
 
//Output the result
        System.out.println(content);
    }
}

The input Excel:

Java: Get Cell Values by Cell Names in Excel

The output result:

Java: Get Cell Values by Cell Names in Excel

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.

Spire.XLS for Java provides you with the ability to shrink text to fit in a cell by using the setShrinkToFit method of the CellStyleObject class. The setShrinkToFit method accepts the following parameter:

boolean: specify whether to shrink text to fit in a cell.

The following example shows how to shrink text to fit in a cell in Excel using Spire.XLS for Java.

import com.spire.xls.*;

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

        //Load the Excel file
        workbook.loadFromFile("Sample.xlsx");

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

        //Get the cell range to shrink text
        CellRange cell = sheet.getRange().get("B2:B3");

        //Enable “shrink to fit”
        cell.getCellStyle().setShrinkToFit(true);

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

The input Excel:

Shrink Text to Fit in a Cell in Excel in Java

The output Excel:

Shrink Text to Fit in a Cell in Excel in Java

Java: Wrap or Unwrap Text in Excel Cells

2022-01-06 06:29:00 Written by Koohji

In the process of manipulating Excel worksheets, sometimes you may encounter the situation where 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 it all. This article will demonstrate how to programmatically wrap or unwrap text in Excel cells 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>15.10.5</version>
    </dependency>
</dependencies>

Wrap or Unwrap Text in Excel cells

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

  • Create a Workbook instance.
  • Load a sample Excel document using Workbook.loadFromFile() method.
  • Get a specific worksheet of the document using Workbook.getWorksheets().get() method.
  • Get a specific cell of the worksheet using Worksheet.getRange().get() method.
  • 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 IStyle interface.
  • Save the document to another file using Workbook.saveToFile() method.
  • Java
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);
    }
}

Java: Wrap or Unwrap Text in Excel Cells

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.

Page 1 of 2
page 1