简体   繁体   English

如何使用Apache POI从特定行读取特定Excel列

[英]How to read a specific excel columns from particular row using Apache POI

I want to store data from excel sheet using Apache POI. 我想使用Apache POI存储来自Excel工作表的数据。

  • In that excel first row consist of employee information (that is an employee name) and the column values consist of employee details (that is an employee address). 在该excel中,第一行包含员工信息(即员工姓名),列值包含员工详细信息(即员工地址)。

  • So each header row (emp name) consist of multiple columns (emp address) 因此,每个标题行(emp名称)都由多个列(emp地址)组成

How do I get row and column values stored in a single entity? 如何获取存储在单个实体中的行和列值?

I'm using Java Spring data. 我正在使用Java Spring数据。

Assuming you are using spring annotatios, you can use the following code to read values from excel sheet. 假设您使用的是弹簧注释,则可以使用以下代码从Excel工作表中读取值。

  @RequestMapping(value = "/excelSheetProgram")
            public String excelSheetProgram(@ModelAttribute("excel"),
                    HttpServletRequest request, RedirectAttributes attributes, HttpServletResponse response, Object command,
                    BindException errors, @RequestParam("Excelfile") MultipartFile Excelfile) throws Exception {

            InputStream inputStream = null;
            inputStream = Excelfile.getInputStream();

            XSSFWorkbook workbook = new XSSFWorkbook(new 
            PushbackInputStream(inputStream));
            XSSFSheet mySheet = workbook.getSheetAt(0);

    // boolean variable for checking when to stop execution of reading from excel fields
            boolean inData = true;

    Iterator<Row> rowIterator = mySheet.iterator();
        rowIterator.next();
        int count = 0;
        for (int i = 0; rowIterator.hasNext() && inData; i++) {
            count++;

            Row row = rowIterator.next();



            // For each row, iterate through each columns
           Iterator<Cell> cellIterator = row.cellIterator();

        while (cellIterator.hasNext()) {
            Cell cell = cellIterator.next();

            // This will change all Cell Types to String
            cell.setCellType(Cell.CELL_TYPE_STRING);
            switch (cell.getCellType()) {
            case Cell.CELL_TYPE_BOOLEAN:

                break;
            case Cell.CELL_TYPE_NUMERIC:

                break;
            case Cell.CELL_TYPE_STRING:



                break;
            }

        }

if (row == null || row.getCell(1) == null || row.getCell(1).getStringCellValue() == null
                    || inData == false) {
                inData = false;
            } 
            else {

                // getting values from excel cells
                employee_name = row.getCell(0).getStringCellValue();
                employee_address = row.getCell(1).getStringCellValue();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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