简体   繁体   中英

Apache poi how to get cell coordinates

I try to get a cell's coordinates, right now I write next code:

for (Row row : sheet) {
   for(Cell cell : row){
      // how to get a cell coordinates?
   }
}

How can I get a cell's coordinates (dx1, dx2, dy1, dy2) ?

The obvious solution was suggested by user2310289 , but that won't work as the iterators skip over blank rows and cells .

So, one option is to iterate manually, taking care of blank cells, and then you'll always know where you cell is, with code something like:

// Decide which rows to process
int rowStart = Math.min(15, sheet.getFirstRowNum());
int rowEnd = Math.max(1400, sheet.getLastRowNum());

for (int rowNum = rowStart; rowNum < rowEnd; rowNum++) {
   Row r = sheet.getRow(rowNum);

   int lastColumn = Math.max(r.getLastCellNum(), MY_MINIMUM_COLUMN_COUNT);

   for (int cn = 0; cn < lastColumn; cn++) {
      Cell c = r.getCell(cn, Row.RETURN_BLANK_AS_NULL);
      if (c == null) {
         // The spreadsheet is empty in this cell
      } else {
         // Do something useful with the cell's contents
         CellReference cr = new CellReference(c);
         System.out.println("Cell at " + rowNum + "," + cn + " found, that's " + cr.formatAsString());
      }
   }
}

Or, if you do want to use the easy iterators, you need to look up the row and cell index from a cell, eg

for (Row r : sheet) {
   for (Cell c : r) {
       int columnNumber = c.getColumnIndex();
       int rowNumber = c.getRow().getRowNum();
       CellReference cr = new CellReference(c);
       System.out.println("Cell at " + rowNum + "," + columnNumber + " found, that's " + cr.formatAsString());
   }
}

the shortest way to get cell address is:

cell.getAddress().formatAsString()

to get sheet name do the following

cell.getSheet().getSheetName()

I have done following code for getting coordinates of the excel cell. Hope this will help you.

public static void searchSheet(String searchText, XSSFSheet sheet)
{

    int flag=0;
    for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++)
    {
        XSSFRow row = sheet.getRow(i);
        for (int j = row.getFirstCellNum(); j < row.getLastCellNum(); j++)
        {
            XSSFCell cell = row.getCell(j);
            String CellData=cell.toString();
            if(searchText.equals(CellData))
            {
                flag=1;
                CellData=row.getCell(j+1).toString();
                System.out.println(CellData);
                System.out.println("String Found At Row="+ i +" and At Column="+j);


            }

         }
        break;
    }

    if(flag==0)
    {
        System.out.println("String Not Found");
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM