2

150 列近くの Excel シートがあります。列名が X である列をフェッチするユーティリティを作成しています。別のスレッドで、XL ワークブックとシートの読み方を見ました。次のコードを記述しました。

        HSSFSheet sheet = workbook.getSheetAt(0);
        Iterator rows = sheet.rowIterator();


        while (rows.hasNext()) 
        {
            HSSFRow row = (HSSFRow) rows.next();
            Iterator cells = row.cellIterator();

            List data = new ArrayList();
            while (cells.hasNext()) 
            {
                HSSFCell cell = (HSSFCell) cells.next();
                data.add(cell);
            }

            sheetData.add(data);
        }
    } 

では、列名を指定して XL シートから正確な列を取得する方法..?

4

4 に答える 4

8

Apache POI API HSSFSheet は行ベースであり、列データを反復して抽出する必要があります。以下のリンクがあなたの質問に答えるかもしれません:

Apache POI API でスプレッドシート列のデータを抽出する

最初のワークシートの行 1 の文字列を検索するように変更されたコード

package projectTest.test;

import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

public class Poi {


    public static void main(String[] args) throws Exception {  
    //test file is located in your project path         
    FileInputStream fileIn = new FileInputStream("test.xls");
    //read file 
    POIFSFileSystem fs = new POIFSFileSystem(fileIn); 
    HSSFWorkbook filename = new HSSFWorkbook(fs);
    //open sheet 0 which is first sheet of your worksheet
    HSSFSheet sheet = filename.getSheetAt(0);

    //we will search for column index containing string "Your Column Name" in the row 0 (which is first row of a worksheet
    String columnWanted = "Your Column Name";
    Integer columnNo = null;
    //output all not null values to the list
    List<Cell> cells = new ArrayList<Cell>();

    Row firstRow = sheet.getRow(0);

    for(Cell cell:firstRow){
        if (cell.getStringCellValue().equals(columnWanted)){
            columnNo = cell.getColumnIndex();
        }
    }


    if (columnNo != null){
    for (Row row : sheet) {
       Cell c = row.getCell(columnNo);
       if (c == null || c.getCellType() == Cell.CELL_TYPE_BLANK) {
          // Nothing in the cell in this row, skip it
       } else {
          cells.add(c);
       }
    }
    }else{
        System.out.println("could not find column " + columnWanted + " in first row of " + fileIn.toString());
    }

    }
}
于 2012-10-06T16:41:03.660 に答える
0

この方法で試すこともできます。ヘッダー行を反復処理できます。

Row headerRow = sheet.get(0);

for (int cellIndex = 0; cellIndex < 150; cellIndex++) {
    Cell cell = row.getCell(cellIndex);
    if (columnName.equals(cell.getStringCellValue())) {
        // do your thing
    }
}

注: セルが空になる場合がある場合は、次を使用します。

Cell cell = row.getCell(cellIndex);

if (cell!=null) {
    if (columnName.equals(cell.getStringCellValue())) {
        // do your thing
    }
}

これが役立つことを願っています!

于 2020-06-21T17:17:10.600 に答える