java 我有一个Excel工作表与多个标题一样:

fnvucqvd  于 2023-04-28  发布在  Java
关注(0)|答案(1)|浏览(126)

我正在尝试用POI java读取Excel。其中我有2行包含列和子列。其中列具有多个子列。其中,来自行3的i具有其中i个子列包含标志是/否的值。
如果行包含“是”,则读取行中的所有值。
如何从Excel中读取一个值包含标题有多个子标题。其中行包含“是”示例:

-------------------------------
|Calumn1  |column2  |column3  |
|Col1|col2|col3|col4|col5|col6|
-------------------------------
|Val1|YES |val2|val3|val4|val5|
|Val2| NO |val2|val3|val4|val5|
ebdffaop

ebdffaop1#

public class ReadExcelFile {

    public static void main(String[] args) throws IOException {
        // Create a FileInputStream object for the Excel file
        FileInputStream fis = new FileInputStream(new File("MyExcelFile.xls"));

        // Create a Workbook object from the FileInputStream object
        HSSFWorkbook workbook = new HSSFWorkbook(fis);

        // Get the first sheet from the workbook
        Sheet sheet = workbook.getSheetAt(0);

        // Get the iterator for the rows in the sheet
        Iterator<Row> rowIterator = sheet.iterator();

        // Iterate over the rows
        while (rowIterator.hasNext()) {
            // Get the current row
            Row row = rowIterator.next();

            // Get the first cell in the row
            Cell cell = row.getCell(0);

            // Get the value of the cell
            String value = cell.getStringCellValue();

            // If the value is "Yes", then print the values of all the cells in the row
            if (value.equals("Yes")) {
                for (int i = 1; i < row.getLastCellNum(); i++) {
                    Cell cell2 = row.getCell(i);
                    System.out.print(cell2.getStringCellValue() + " ");
                }
                System.out.println();
            }
        }

        // Close the workbook
        workbook.close();
    }

}

此代码将读取Excel文件“MyExcelFile。xls”并打印第一个单元格包含值“Yes”的所有行的值。
下面是代码的解释:

The first line creates a FileInputStream object for the Excel file.
The second line creates a Workbook object from the FileInputStream object.
The third line gets the first sheet from the workbook.
The fourth line gets the iterator for the rows in the sheet.
The fifth line iterates over the rows.
The sixth line gets the first cell in the row.
The seventh line gets the value of the cell.
The eighth line checks if the value is "Yes".
If the value is "Yes", then the ninth line prints the values of all the cells in the row.
The tenth line closes the workbook.

相关问题