当读取 Excel 文件中的列时,该程序读取数据和空列

When reading a column in Excel file, this program reads data and empty columns

我想读取 Excel 文件并跳过空行。我的代码读取数据和空白单元格。如何跳过空白行,我正在使用 Apache POI。 帮我解决这个问题

package com.company;
import org.apache.commons.compress.archivers.dump.InvalidFormatException;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.String;
import java.util.Iterator;
import java.util.Scanner;
public class Main {
    public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);

        XSSFWorkbook library_table = new XSSFWorkbook(new FileInputStream("C:\Users\admin\Desktop\Курсовая\Table for course work.xlsx"));
        XSSFSheet library_sheet = library_table.getSheet("Library");
        Iterator rowiter = ((XSSFSheet) library_sheet).rowIterator();
        boolean continue_first_row = true;
        System.out.println("1 - Name\n2 - Author\n3 - Date of publishing");
        System.out.print("Choose type of search: ");
        int choice = in.nextInt(), count = 0;

        while(rowiter.hasNext()){
            XSSFRow row = (XSSFRow) rowiter.next();
            if (count == 0){
                count++;
                continue;
            }
            else {
                System.out.println(row.getCell(choice));
            }

        }
}
}

Sheet.rowIterator 不包含完全空的行。但它当然包含仅填充了部分单元格的行。它包含具有格式的行或具有格式的单元格,即使这些单元格为空也是如此。

因此,如果需要跳过空单元格,那么您的程序必须检查找到的单元格是否为空。最简单的可能性是检查 Cell 是否为 nullCell.toString 等于空 String.

...
  while(rowiter.hasNext()) { // does not contain totally empty rows
   XSSFRow row = (XSSFRow) rowiter.next();
   if (count == 0) { //skip header row
    count++;
    continue;
   } else {
    XSSFCell cell = row.getCell(choice);
    if (cell == null || "".equals(cell.toString())) { // check whether cell is empty
     // cell is empty
    } else {
     System.out.println(cell.toString());
    }
   }
  }
...

注意:依赖 Cell.toString 不是好的做法。而是使用 DataFormatter 将单元格值作为 String.

示例:

...
import org.apache.poi.ss.usermodel.DataFormatter;
...
  while(rowiter.hasNext()) { // does not contain totally empty rows
   XSSFRow row = (XSSFRow) rowiter.next();
   if (count == 0) { //skip header row
    count++;
    continue;
   } else {
    XSSFCell cell = row.getCell(choice);
    String cellValue = dataFormatter.formatCellValue(cell);
    if ("".equals(cellValue)) { // check whether cell is empty
     // cell is empty
    } else {
     System.out.println(cellValue);
    }
   }
  }
...