Referencing Excel cell and range in Java

An Excel cell or range of cells can be referenced by using either names or indexes. If using indexes, you can specify absolute or relative position.

The following example shows various techniques for referencing ExcelCell and CellRange objects in Java, which can be used in GemBox.Spreadsheet for Java library.

Excel cell and range referencing with GemBox.Spreadsheet for Java
Screenshot of Excel cell and range referencing with GemBox.Spreadsheet for Java
import com.gembox.spreadsheet.*;

class Program {

    public static void main(String[] args) throws {
        // If using Professional version, put your serial key below.

        ExcelFile workbook = new ExcelFile();
        ExcelWorksheet worksheet = workbook.addWorksheet("Cell Referencing");

        worksheet.getCell(0, 0).setValue("Cell referencing examples:");

        worksheet.getCell("B2").setValue("Cell B2.");
        worksheet.getCell(6, 0).setValue("Cell in row 7 and column A.");

        worksheet.getRow(2).getCell(0).setValue("Cell in row 3 and column A.");
        worksheet.getRow("4").getCell("B").setValue("Cell in row 4 and column B.");

        worksheet.getColumn(2).getCell(4).setValue("Cell in column C and row 5.");
        worksheet.getColumn("AA").getCell("6").setValue("Cell in AA column and row 6.");

        // Referencing Excel row's cell range.
        CellRange cellRange = worksheet.getRow(7).getCells();


        // Referencing Excel column's cell range.
        cellRange = worksheet.getColumn(7).getCells();


        // Referencing arbitrary Excel cell range.
        cellRange = worksheet.getCells().getSubrange("I2", "L8");
        cellRange.getStyle().getBorders().setBorders(MultipleBorders.outside(), SpreadsheetColor.fromArgb(0, 0, 128), LineStyle.DASHED);

        cellRange.get(0, 0).setValue("I2");
        cellRange.get(4).setValue("I3"); // Cell range width is 4 (I J K L).

        // Set column widths and some print options
        double[] columnWidths = new double[] { 175, 174, 174, 24, Double.NaN, Double.NaN, Double.NaN, 54, 19, 81 };
        for (int i = 0; i < columnWidths.length; i++)
            if (!Double.isNaN(columnWidths[i]))
                worksheet.getColumn(i).setWidth(columnWidths[i], LengthUnit.PIXEL);

        worksheet.getPrintOptions().setPrintHeadings(true);"Cell Referencing.%OutputFileType%");

Want more?

Next example GitHub

Check the next example or select an example from the menu. You can also download our examples from the GitHub.

Like it?

Download Buy

If you want to try the GemBox.Spreadsheet for Java yourself, you can download the free version. It delivers the same performance and set of features as the professional version, but with some operations limited. To remove the limitation, you need to purchase a license.