【问题标题】:Skipping Blank Excel Cells in Apache POI跳过 Apache POI 中的空白 Excel 单元格
【发布时间】:2012-05-01 22:59:12
【问题描述】:

我是 Apache POI 的新手,但我想做的是通过 Excel 文件 (.xls) 读取并将其放入 ArrayList 进行存储,以便以后进行操作。我可以得到整张纸,但我的问题是:我得到了整张纸(~54183 行)。

我想跳过类型为 3 的空白单元格。出于某种原因,当我 system.out.print ArrayList 时,其中包含所有空白单元格。

有没有办法跳过这些而不将它们添加到我正在尝试创建的 ArrayList 中?

我有以下代码:

public ArrayList readExcelFile(String filePath) throws IOException {
    ArrayList cellVectorHolder = new ArrayList();
    try {
        FileInputStream inputFile = new FileInputStream(filePath);
        POIFSFileSystem myFileSystem = new POIFSFileSystem(inputFile);
        HSSFWorkbook wkbk = new HSSFWorkbook(myFileSystem);
        wb = wkbk;
        for (int i = 0; i < wb.getNumberOfSheets(); i++) {
            HSSFSheet wkSheet = wkbk.getSheetAt(i);
            for (Row row : wkSheet) {
                ArrayList cellVector = new ArrayList();
                for (Cell cell : row) {
                    if(cell.getCellType() != 3){
                        cellVector.add(cell);
                    }
                }
                cellVectorHolder.add(cellVector);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return cellVectorHolder;
}

不要介意 ArrayList 的名称...我一直在使用 Vectors,直到我最终发现它们从 1.2 或类似的版本开始就被贬值了。

【问题讨论】:

    标签: java apache-poi


    【解决方案1】:

    在将单元格添加到列表之前,您可以检查单元格的值。比如:

    if (cell.getStringCellValue() != null &&  cell.getStringCellValue().length() != 0) {   
        cellVector.add(cell); 
    }
    

    只有在有内容时才添加单元格。

    【讨论】:

    • 是的,这就是我最终求助的方法。一些 if else 语句来检查它。我只是希望 POI 有一些简短的干净方式。不过感谢您朝着正确的方向前进!
    • 如果单元格类型不是文本(例如数字),cell.getStringCellValue() 将抛出 IllegalStateException。
    【解决方案2】:

    我认为你应该遍历行和单元格,这样 POI 甚至不会给你空单元格。

    检查HSSFSheet.iterator(),它遍历工作表中的所有行。 然后Row.cellIterator() 遍历该行中的单元格。

    你基本上完成了。

    如果您打算保留旧的结果变量,您的两个内部循环将变为:

    for (Iterator<Row> rit = wkSheet.iterator();rit.hasNext();) {
        ArrayList cellVector = new ArrayList();
        for(Iterator<Cell> cit = rit.next().cellIterator(); cit.hasNext(); ) { 
                cellVector.add(cit.next());
        }
        cellVectorHolder.add(cellVector);
    }
    

    【讨论】:

    • 您可能还想对照 CELL_TYPE_BLANK 检查类型 - Excel 经常会在文件中留下曾经使用过的单元格,现在该类型为空。
    • 嗯,即使您检查 CELL_TYPE_BLANK?我从来没有经历过这样的事情。当我阅读您的代码时,我有点以为您特意包含了空单元格。
    • 所以我回去用迭代器做了 Cell_Type_Blank,这仍然会将空白单元格放入我的 arrayList 中,但只能从一张表中。我为“”添加了另一个检查,这似乎摆脱了它们。感谢 esej 的帮助!
    • 酷。类型为 CELL_TYPE_BLANK 和 cellValue "" 的单元格应该来自源代码(例如,有人手动编辑了一个 excel 文件)。完全空的单元格不会保存在文件中。但是,如果那里有一个值,然后该值被删除,则单元格信息将在文件中。
    【解决方案3】:
    Try the following code with excel as 
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.ss.usermodel.Sheet;
    import org.apache.poi.ss.usermodel.Workbook;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    public class excelDataReader {
    public static void main(String[] args) {
        List<Info> infoList = extractInfo();
        for (Info info : infoList) {
            System.out.println(info);
        }
    }
    public static List<Info> extractInfo() {
        List<Info> infoList = new ArrayList<Info>();
        Workbook wb = null;
        try {
            wb = new XSSFWorkbook(new FileInputStream(new         
     File("C:\\Users\\rrr\\Downloads\\contacts.xlsx")));
            Sheet sheet = wb.getSheetAt(0);
            boolean skipHeader = true;
            for (Row row : sheet) {
                if (skipHeader) {
                    skipHeader = false;
                    continue;
                }
                List<Cell> cells = new ArrayList<Cell>();
                int lastColumn = Math.max(row.getLastCellNum(), 5);// because my
                                                                    // excel
                                                                    // sheet has
                                                                    // max 5
                                                                    // columns,
                                                                    // in case
                                                                    // last
                                                                    // column is
                                                                    // empty
                                                                    // then
                                                                    // row.getLastCellNum()
                                                                    // will
                                                                    // return 4
                for (int cn = 0; cn < lastColumn; cn++) {
                    Cell c = row.getCell(cn, Row.RETURN_BLANK_AS_NULL);
                    cells.add(c);
                }
                Info info = extractInfoFromCell(cells);
                infoList.add(info);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (wb != null) {
                try {
                    wb.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return infoList;
    }
    private static Info extractInfoFromCell(List<Cell> cells) {
        Info info = new Info();
        Cell nameCell = cells.get(0);
        if (nameCell != null) {
            nameCell.setCellType(Cell.CELL_TYPE_STRING);
            info.setName(nameCell.getStringCellValue());
        }
        Cell mobileCell = cells.get(1);
        if (mobileCell != null) {
            mobileCell.setCellType(Cell.CELL_TYPE_STRING);
            info.setMobile(mobileCell.getStringCellValue());
        }
        Cell phoneCell = cells.get(2);
        if (phoneCell != null) {
            phoneCell.setCellType(Cell.CELL_TYPE_STRING);
            info.setPhone(phoneCell.getStringCellValue());
        }
        Cell permAddressCell = cells.get(3);
        if (permAddressCell != null) {
            permAddressCell.setCellType(Cell.CELL_TYPE_STRING);
            info.setPermAddress(permAddressCell.getStringCellValue());
        }
        Cell commAddressCell = cells.get(4);
        if (commAddressCell != null) {
            commAddressCell.setCellType(Cell.CELL_TYPE_STRING);
            info.setCommAddress(commAddressCell.getStringCellValue());
        }
        return info;
    }
    

    } 包cmprocesser.cmprocesser;

    import java.io.File; 
    import java.io.FileInputStream;  
    import java.io.IOException;  
    import org.apache.poi.xssf.usermodel.XSSFCell;
    import org.apache.poi.xssf.usermodel.XSSFSheet;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.LinkedHashMap;
    import java.util.List;
    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.ss.usermodel.Comment;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.ss.usermodel.Sheet;
    import org.apache.poi.ss.usermodel.Workbook;
    
    public class Info {
        private String name;
        private String mobile;
        private String phone;
        private String permAddress;
        private String commAddress;
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getMobile() {
            return mobile;
        }
        public void setMobile(String mobile) {
            this.mobile = mobile;
        }
        public String getPhone() {
            return phone;
        }
        public void setPhone(String phone) {
            this.phone = phone;
        }
        public String getPermAddress() {
            return permAddress;
        }
        public void setPermAddress(String permAddress) {
            this.permAddress = permAddress;
        }
        public String getCommAddress() {
            return commAddress;
        }
        public void setCommAddress(String commAddress) {
            this.commAddress = commAddress;
        }
        @Override
        public String toString() {
            return "Info [Name=" + name + ", Mobile=" + mobile + ", Phone=" + phone + ", Permanent Address=" + permAddress
                    + ", Communication Address=" + commAddress + "]";
        }
    }
    

    【讨论】:

      【解决方案4】:

      试试这个

      List cellDataList = new ArrayList
      HSSFWorkbook workBook = new HSSFWorkbook(fsFileSystem);
                                  HSSFSheet hssfSheet = workBook.getSheetAt(0);
                                  Iterator rowIterator = hssfSheet.rowIterator();
      
                                  int lineNumber = 0;
                                  while (rowIterator.hasNext())
                                  {
                                      HSSFRow hssfRow = (HSSFRow) rowIterator.next();
      
                                      lineNumber++;
                                      if(lineNumber==1){continue;}
      
      
      
                                      Iterator iterator = hssfRow.cellIterator();
                                      List cellTempList = new ArrayList();
                                      int current = 0, next = 1;
                                      while (iterator.hasNext())
                                      {
                                          HSSFCell hssfCell = (HSSFCell) iterator.next();
      
                                          current = hssfCell.getColumnIndex();
      
      
                                          if(current<next){                                   
      
      
                                          }
                                          else{
      
                                              int loop = current-next;
      
                                              for(int k=0;k<loop+1;k++){
      
      
                                                  cellTempList.add(null);
                                                  next = next + 1;
                                              }
                                          }
      
                                          cellTempList.add(hssfCell);
      
      
      
                                          next = next + 1;
      
      
      
                                      }
                                      cellDataList.add(cellTempList);
                                  }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-06-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多