如何将HSSF行保存为String java POI

时间:2016-05-05 13:17:56

标签: java arraylist apache-poi

我正在尝试根据关键字过滤电子表格。我想将行存储在多维字符串数组(单元格值和行)中。我似乎无法让每个细胞成为一个独立的元素。所有数组中的所有单元格都被添加到一个数组中:

以下是代码:

////Adding each filtered row to an ArrayList

FileInputStream fis = new FileInputStream(new File("myfile.xls"));
        HSSFWorkbook      workBook = new HSSFWorkbook (fis);
        HSSFSheet         sheet    = workBook.getSheetAt (0);

        List<HSSFRow> filteredRows = new ArrayList<HSSFRow>();
        ArrayList<List<HSSFRow>> TwoD = new ArrayList<List<HSSFRow>>();
        Iterator<Row> rows= sheet.rowIterator(); 
        while (rows.hasNext ()){
        HSSFRow row = (HSSFRow) rows.next ();  
        Iterator<Cell> cells = row.cellIterator (); 
         while (cells.hasNext ()){
             HSSFCell cell = (HSSFCell) cells.next (); 
              if (cell.toString().contains("GHH")) {
                  filteredRows.add(row);
                }
        }
         }

///////  Now iterating through the filteredRows arrayList and turn it into multidimensional String array

        ArrayList<String> in =new ArrayList<String>();
        ArrayList<List<String>> out = new ArrayList<List<String>>();
        for (HSSFRow n:filteredRows){

            Iterator<Cell> cells = n.cellIterator (); 
             while (cells.hasNext ()){
                 HSSFCell cell = (HSSFCell) cells.next (); 
                 in.add(cell.toString());

             }
             out.add(in);
        }

        workBook.close();

1 个答案:

答案 0 :(得分:1)

您的问题是您没有在行之间重置in数组列表

您需要将其更改为:

ArrayList<List<String>> out = new ArrayList<List<String>>();
for (HSSFRow n:filteredRows){
    ArrayList<String> in =new ArrayList<String>();
    for (Cell cell : n) {

每次都创建一个新列表来保存您的单元格。

注意 - 此代码不起作用:

ArrayList<String> in =new ArrayList<String>();
ArrayList<List<String>> out = new ArrayList<List<String>>();
for (HSSFRow n:filteredRows){
    for (Cell cell : n) {
       // Logic here
    }
    out.add(in);
    in.clear();
}

因为您每次都要添加相同的对象,所以最后只会包含out包含最后一行的多个副本!当您保留对数组的引用时,它们需要是单独的对象