我有一个包含6663行的Excel文件。我想读取Excel文件中的所有行和列,并在Eclipse控制台上打印出来。以下是我尝试过的方法:
public class ExcelReader {
public static final String SAMPLE_XLSX_FILE_PATH = "K:\\Documents\\Project\\Netword_GUI\\Netword_GUI\\src\\libs\\cc2017.xlsx";
public static void main(String[] args) throws IOException, InvalidFormatException {
// Creating a Workbook from an Excel file (.xls or .xlsx)
Workbook workbook = WorkbookFactory.create(new File(SAMPLE_XLSX_FILE_PATH));
// Retrieving the number of sheets in the Workbook
System.out.println("Workbook has " + workbook.getNumberOfSheets() + " Sheets : ");
/*
=============================================================
Iterating over all the sheets in the workbook (Multiple ways)
=============================================================
*/
// You can obtain a sheetIterator and iterate over it
Iterator<Sheet> sheetIterator = workbook.sheetIterator();
System.out.println("Retrieving Sheets using Iterator");
while (sheetIterator.hasNext()) {
Sheet sheet = sheetIterator.next();
//System.out.println(sheet.getRow(0));
System.out.println("=> " + sheet.getSheetName());
}
// Getting the Sheet at index zero
Sheet sheet = workbook.getSheetAt(0);
// Create a DataFormatter to format and get each cell's value as String
DataFormatter dataFormatter = new DataFormatter();
// You can obtain a rowIterator and columnIterator and iterate over them
System.out.println("\n\nIterating over Rows and Columns using Iterator\n");
Iterator<Row> rowIterator = sheet.rowIterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
// Now let's iterate over the columns of the current row
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
String cellValue = dataFormatter.formatCellValue(cell);
System.out.print(cellValue + "\t");
}
System.out.println();
}
if (sheet.getActiveCell() == null) {
// Closing the workbook
workbook.close();
}
}
}
这段代码的意图是显示所有行和列。目前,这段代码只显示了大约200行,但所有这些行的列都按预期显示。它似乎也以随机顺序显示行,尽管每次运行时相同的行都以相同的随机顺序显示。我希望能够提供任何解决方案,以便按正确的顺序(包括标题行)显示所有6663行。谢谢您提前。
Iterator
也有完全空的行吗?它不会。但是其他情况下:Excel文件cc2017.xlsx
从哪里来?使用了什么软件创建它?以及使用了什么apache poi
版本?早期的apache poi
版本只读取设置了行号的行。 如果是这样,XML看起来像<row r="3" ...>
。但是属性r
是可选的,某些第三方软件可能不总是设置它。早期的apache poi
版本无法在没有行号的情况下读取这些行。 - Axel Richter