How to get value from a specific cell of an xlsx file using java apache poi

前端 未结 5 1379
一生所求
一生所求 2020-12-30 08:54

I am writing a java program to read an excel sheet (xlsx) using apache poi. I am able to iterate through all the cells and get all the values. But I am unable to get a spec

相关标签:
5条回答
  • 2020-12-30 09:12

    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"));
    
    0 讨论(0)
  • 2020-12-30 09:18
    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());
        });
    
    }
    }
    
    0 讨论(0)
  • 2020-12-30 09:31

    To get a value from a specific cell in excel you can use the below code line.

    wb.getSheetAt(0).getRow(1).getCell(1);
    
    0 讨论(0)
  • 2020-12-30 09:31

    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")
    
    0 讨论(0)
  • 2020-12-30 09:34

    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.

    0 讨论(0)
提交回复
热议问题