我有一个包含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行,包括标题(第一行)。预先谢谢你。