简体   繁体   中英

How to get value from a specific cell from XLSX file using java Apache POI library

I am writing a Java program to read data from excel sheet (having XLSX extension) using Apache POI library. I am able to iterate through all the cells and get all the values. But I am unable to get a specific cell value, say E10. Is there any way to do this?

Please see the code below that I used for iterating through the cells.

package application;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ReadFromXLSX {
    public static void readXLSXFile() throws IOException
    {
        InputStream ExcelFileToRead = new FileInputStream("C:\\Test.xlsx");
        XSSFWorkbook  wb = new XSSFWorkbook(ExcelFileToRead);
        XSSFWorkbook test = new XSSFWorkbook(); 
        XSSFSheet sheet = wb.getSheetAt(0);
        XSSFRow row; 
        XSSFCell cell;
        Iterator rows = sheet.rowIterator();
        while (rows.hasNext())
        {
            row=(XSSFRow) rows.next();
            Iterator cells = row.cellIterator();
            while (cells.hasNext())
            {
                cell=(XSSFCell) cells.next();   
                if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING)
                {
                    System.out.print(cell.getStringCellValue()+" ");
                }
                else if(cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC)
                {
                    System.out.print(cell.getNumericCellValue()+" ");
                }
                else
                {
                }
            }
            System.out.println();
        }
    }   
}

For example, to get E10 of the first worksheet:

wb.getSheetAt(0).getRow(9).getCell(4); 

Note: subtract one because the indices are null-based.

You can also use this convenience method to map E to 4.

wb.getSheetAt(0).getRow(9).getCell(CellReference.convertColStringToIndex("E"));

要从 excel 中的特定单元格获取值,您可以使用以下代码行。

wb.getSheetAt(0).getRow(1).getCell(1);

XSSFSheet has the method getRow(int rownum) It returns the logical row ( 0-based). If you ask for a row that is not defined you get a null. This is to say row 4 represents the fifth row on a sheet.

Once you get the row, you can call getCell(int cellnum) method of XSSFRow object. It returns the cell at the given (0 based) index.

Just version-up the getCell method

public XSSFCell getCell(String cellName){
    Pattern r = Pattern.compile("^([A-Z]+)([0-9]+)$");
    Matcher m = r.matcher(cellName);
    XSSFWorkbook wb = new XSSFWorkbook();
    if(m.matches()) {
        String columnName = m.group(1);
        int rowNumber = Integer.parseInt(m.group(2));
        if(rowNumber > 0) {
            return wb.getSheetAt(0).getRow(rowNumber-1).getCell(CellReference.convertColStringToIndex(columnName));
        }
    }
    return null;
}

Now you can get the cell easily by this line

getCell("E10")
public class XmlFileRead {

public static void main(String[] args) throws IOException {
    FileInputStream fi = new FileInputStream("abc.xls");
    ArrayList<EmployeeVo> al = new ArrayList<>();
    EmployeeVo evo = null;
    Scanner scanner = null;

    Workbook wb = new XSSFWorkbook(fi);
    Sheet sh = wb.getSheet("Sheet0");
    int starRow = sh.getFirstRowNum();
    int endRow = sh.getLastRowNum();

    for (int i = starRow + 1; i < endRow; i++) {
        scanner = new Scanner(System.in);
        evo = new EmployeeVo();
        Cell c = wb.getSheetAt(0).getRow(i).getCell(1);
        evo.setEmployeeId((int) c.getNumericCellValue());

        Cell c2 = wb.getSheetAt(0).getRow(i).getCell(2);
        evo.setEmployeeName(c2.toString());
        // add to collection
        al.add(evo);
    } // for

    al.forEach(i -> {
        System.out.println(i.getEmployeeId() + " " + i.getEmployeeName());
    });

}
}

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