簡體   English   中英

使用Apache POI讀取Excel文件並將其存儲到數組中

[英]Reading Excel file using apache poi and storing them into arrays

我是編程世界的新手。 好吧,即時通訊試圖使用apache-poi庫讀取Excel文件(5行,5列)。 我實際上有兩個實現相同的問題。 在第一個代碼段中,我只是讀取了我的excel文件並將其打印到控制台中。

但是現在我試圖將讀取的excel數據保存到數組中。 所以我想在動態獲取Excel行和列大小后設置數組大小。 但是令我驚訝的是,當我執行第二個代碼片段時,即使輸入的excel文件中只有5行,5列,“ while(cellIterator.hasNext()”)仍會連續迭代。請指導我哪里出錯了。

感謝侯賽因代碼片段1(按預期方式工作)

public static void main(String args[]) {
    readFile(ConfigReader.readConfigValues("XLS-path"),
            ConfigReader.readConfigValues("SheetName"));
}

public static void readFile(String filePath, String sheetName) {

    try {

        FileInputStream file = new FileInputStream(new File(filePath));

        // Get the workbook instance for XLS file
        HSSFWorkbook workbook = new HSSFWorkbook(file);

        // Get first sheet from the workbook
        HSSFSheet sheet = workbook.getSheet(sheetName);

        // Iterate through each rows from first sheet
        Iterator<Row> rowIterator = sheet.iterator();
        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();

            // For each row, iterate through each columns
            Iterator<Cell> cellIterator = row.cellIterator();
            while (cellIterator.hasNext()) {

                Cell cell = cellIterator.next();

                switch (cell.getCellType()) {
                case Cell.CELL_TYPE_BOOLEAN:
                    System.out.print(cell.getBooleanCellValue() + "\t\t");
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    System.out.print(cell.getNumericCellValue() + "\t\t");
                    break;
                case Cell.CELL_TYPE_STRING:
                    System.out.print(cell.getStringCellValue() + "\t\t");
                    break;
                }
            }
            System.out.println("");
        }
        file.close();
        FileOutputStream out = new FileOutputStream(new java.io.File(
                "G:\\test1.xls"));
        workbook.write(out);
        out.close();

    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

代碼段2(無法正常工作)

public static void main(String args[]) {
    readFile(ConfigReader.readConfigValues("XLS-path"),
            ConfigReader.readConfigValues("SheetName"));
}

public static void readFile(String filePath, String sheetName) {

    try {

        FileInputStream file = new FileInputStream(new File(filePath));

        // Get the workbook instance for XLS file
        HSSFWorkbook workbook = new HSSFWorkbook(file);

        // Get first sheet from the workbook
        HSSFSheet sheet = workbook.getSheet(sheetName);

        // Iterate through each rows from first sheet
        Iterator<Row> rowIterator = sheet.iterator();
        String[][] excelArray = null;
        excelArray = new String[getRowCount(rowIterator, excelArray)][];

        file.close();
        FileOutputStream out = new FileOutputStream(new java.io.File(
                "G:\\test1.xls"));
        workbook.write(out);
        out.close();

    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public static int getRowCount(Iterator<Row> rowIterator,
        String[][] excelArray) {
    int sizeArrayRow = 0;
    while (rowIterator.hasNext()) {
        Row row = rowIterator.next();
        excelArray[sizeArrayRow] = new String[getColCount(row)];
        sizeArrayRow++;

    }

    return sizeArrayRow;
}

public static int getColCount(Row row) {

    int sizeArrayCol = 0;
    // For each row, iterate through each columns
    Iterator<Cell> cellIterator = row.cellIterator();
    while (cellIterator.hasNext()) {
        sizeArrayCol++;
    }
    return sizeArrayCol;
}

要了解Java迭代器的工作方式,請閱讀以下內容: http ://www.tutorialspoint.com/java/java_using_iterator.htm特別要注意hasNext()和next()之間的區別

您正在檢查:

while (cellIterator.hasNext())

但您永遠不會從該迭代器“讀取”任何內容,因此它保持在當前位置,並為hasNext始終返回true。 您可以使用以下方法將其向前推:

cellIterator.next();

另外,我認為代碼很混亂並且很難遵循。 考慮使用列表而不是String數組。 這樣,您可以在不預先知道其大小的情況下進行填充。

 public class ExcelToArrayConverter {
        public String[] excelvalue(String columnWanted,int sheet_no){
            int i=0;
            String[] column_content_array =new String[140];
            try{
                int instindicator=-1;       
                InputStream fileIn = this.getClass().getClassLoader().getResourceAsStream("db.xls");
                POIFSFileSystem fs = new POIFSFileSystem(fileIn);
                HSSFWorkbook filename = new HSSFWorkbook(fs);
                HSSFSheet sheet = filename.getSheetAt(sheet_no);                                                // in the row 0 (which is first row of a work sheet)                                                    // search for column index containing string "Inst_Code"
                Integer columnNo = null;
                Integer rowNo = null;
                List<Cell> cells = new ArrayList<Cell>();
                Row firstRow = sheet.getRow(0);
                for (Cell cell : firstRow) {
                    if (cell.getStringCellValue().equals(columnWanted)) {
                        columnNo = cell.getColumnIndex();
                        rowNo=cell.getRowIndex();
                    }
                }
                if (columnNo != null) {
                    for (Row row : sheet) {
                        Cell c = row.getCell(columnNo);
                        String cell_value=""+c;
                        cell_value=cell_value.trim();
                        try{
                            if((!cell_value.equals(""))&&(!cell_value.equals("null"))&&(!cell_value.equals(columnWanted))){ 
                                column_content_array[i]=cell_value;
                                i++;
                            }}
                        catch(Exception e){
                        }

                    }
                    return column_content_array;
                }}
            catch(Exception ex){
                return column_content_array;
            }
            return column_content_array;

        }}

 This method will convert any specific column of a specific sheet to an array.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM