Java 使用ApachePOI读取Excel文件并将其存储到数组中

Java 使用ApachePOI读取Excel文件并将其存储到数组中,java,apache-poi,Java,Apache Poi,我是编程界的新手。嗯,我正在尝试使用ApachePOI库读取excel文件(5行,5列)。我实际上有两个相同问题的实现。 在第一个代码段中,我只是读取excel文件并将它们打印到控制台中 不过,现在我正试图将读取的excel数据保存到一个数组中。因此,我想在动态获取excel行和列大小后设置数组大小。但令我惊讶的是,当我执行第二个代码段时,“while(cellIterator.hasNext()”似乎在不断迭代,即使我的输入excel文件中只有5行5列。请告诉我哪里出错了 谢谢 侯赛因 代码段

我是编程界的新手。嗯,我正在尝试使用ApachePOI库读取excel文件(5行,5列)。我实际上有两个相同问题的实现。 在第一个代码段中,我只是读取excel文件并将它们打印到控制台中

不过,现在我正试图将读取的excel数据保存到一个数组中。因此,我想在动态获取excel行和列大小后设置数组大小。但令我惊讶的是,当我执行第二个代码段时,“while(cellIterator.hasNext()”似乎在不断迭代,即使我的输入excel文件中只有5行5列。请告诉我哪里出错了

谢谢 侯赛因 代码段1(按预期工作)

publicstaticvoidmain(字符串参数[]){
readFile(ConfigReader.readConfigValues(“XLS路径”),
ConfigReader.readConfigValues(“SheetName”);
}
公共静态void readFile(字符串文件路径、字符串名称){
试一试{
FileInputStream file=newfileinputstream(新文件(filePath));
//获取XLS文件的工作簿实例
HSSF工作簿=新的HSSF工作簿(文件);
//从工作簿中获取第一张工作表
HSSFSheet sheet=workbook.getSheet(sheetName);
//从第一张图纸开始遍历每行
迭代器rowIterator=sheet.Iterator();
while(roweiterator.hasNext()){
行=行迭代器。下一步();
//对于每一行,遍历每一列
迭代器cellIterator=row.cellIterator();
while(cellIterator.hasNext()){
Cell=cellIterator.next();
开关(cell.getCellType()){
case Cell.Cell\u类型\u布尔值:
System.out.print(cell.getBooleanCellValue()+“\t\t”);
打破
case Cell.Cell\u类型\u数值:
System.out.print(cell.getNumericCellValue()+“\t\t”);
打破
case Cell.Cell\u类型\u字符串:
System.out.print(cell.getStringCellValue()+“\t\t”);
打破
}
}
System.out.println(“”);
}
file.close();
FileOutputStream out=新的FileOutputStream(新的java.io.File(
“G:\\test1.xls”);
练习册。写(出);
out.close();
}捕获(FileNotFoundException e1){
e1.printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
}
代码段2(未按预期工作)

publicstaticvoidmain(字符串参数[]){
readFile(ConfigReader.readConfigValues(“XLS路径”),
ConfigReader.readConfigValues(“SheetName”);
}
公共静态void readFile(字符串文件路径、字符串名称){
试一试{
FileInputStream file=newfileinputstream(新文件(filePath));
//获取XLS文件的工作簿实例
HSSF工作簿=新的HSSF工作簿(文件);
//从工作簿中获取第一张工作表
HSSFSheet sheet=workbook.getSheet(sheetName);
//从第一张图纸开始遍历每行
迭代器rowIterator=sheet.Iterator();
字符串[][]excelArray=null;
excelArray=新字符串[getRowCount(rowIterator,excelArray)]];
file.close();
FileOutputStream out=新的FileOutputStream(新的java.io.File(
“G:\\test1.xls”);
练习册。写(出);
out.close();
}捕获(FileNotFoundException e1){
e1.printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
}
公共静态int getRowCount(迭代器rowIterator,
字符串[][]EXCEL数组){
int sizeArrayRow=0;
while(roweiterator.hasNext()){
行=行迭代器。下一步();
excelArray[sizeArrayRow]=新字符串[getColCount(row)];
sizerarayrow++;
}
返回sizerarayrow;
}
公共静态int getColCount(行){
int-sizeArrayCol=0;
//对于每一行,遍历每一列
迭代器cellIterator=row.cellIterator();
while(cellIterator.hasNext()){
sizeraraycol++;
}
返回Sizeraraycol;
}

要了解Java迭代器的工作原理,请阅读以下内容: 特别要注意hasNext()和next()之间的区别

您正在检查:

while (cellIterator.hasNext())
但您永远不会“读取”该迭代器中的任何内容,因此它将保持在当前位置,并不断为下一步返回true。 您可以使用以下方法将其向前推:

cellIterator.next();

也认为,代码是凌乱的,很难跟随的。而不是字符串数组,考虑使用列表。这样,你可以事先不知道它的大小填充它。

看看java迭代器是如何工作的,请阅读:
 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.
特别要注意hasNext()和next()之间的区别

您正在检查:

while (cellIterator.hasNext())
但您永远不会“读取”该迭代器中的任何内容,因此它将保持在当前位置,并不断为下一步返回true。 您可以使用以下方法将其向前推:

cellIterator.next();

同样,我认为代码是凌乱的和难以跟随的。而不是一个字符串数组,考虑使用一个列表。这样,你就可以预先填充它而不知道它的大小。

<代码>公共类Excel。
 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.
公共字符串[]excelvalue(需要字符串列,内部工作表编号){ int i=0; 字符串[]列内容数组=新字符串[140]; 试一试{ int institicator=-1; InputStream fileIn=this.getClass().getClassLoader().getResourceAsStream(“db.xls”); POIFSFileSystem fs=新的POIFSFileSystem(fileIn); HSSF工作簿文件名=新的HSSF工作簿(fs); HSSFSheet sheet sheet=filename.getSheetAt(sheet_no);//第0行(工作表的第一行)//搜索包含字符串“Inst_Code”的列索引 我