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 the 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%");

See also

Next steps

GemBox.Spreadsheet for Java is a component that enables you to read, write, edit and convert spreadsheet files from your applications using one simple API.

Download Buy