共計 1412 個字符,預計需要花費 4 分鐘才能閱讀完成。
要在 Java 中獲取 Excel 數據,可以使用 Apache POI 庫。以下是獲取 Excel 數據的基本步驟:
- 導入 Apache POI 庫的依賴項。在 Maven 項目中,可以在 pom.xml 文件中添加以下依賴項:
<dependencies>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
</dependencies>
- 創建一個
Workbook
對象,打開 Excel 文件:
File file = new File("path/to/excel.xlsx"); // 替換為實際的 Excel 文件路徑
Workbook workbook = WorkbookFactory.create(file);
- 獲取要讀取的工作表:
Sheet sheet = workbook.getSheetAt(0); // 獲取第一個工作表
- 遍歷工作表中的每一行和每一列,并獲取單元格的值:
for (Row row : sheet) {for (Cell cell : row) {String cellValue = cell.getStringCellValue();
System.out.print(cellValue + "\t");
}
System.out.println(); // 換行
}
完整代碼示例:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class ExcelReader {public static void main(String[] args) {try {File file = new File("path/to/excel.xlsx"); // 替換為實際的 Excel 文件路徑
FileInputStream fis = new FileInputStream(file);
Workbook workbook = new XSSFWorkbook(fis);
Sheet sheet = workbook.getSheetAt(0); // 獲取第一個工作表
for (Row row : sheet) {for (Cell cell : row) {String cellValue = cell.getStringCellValue();
System.out.print(cellValue + "\t");
}
System.out.println(); // 換行
}
workbook.close();
fis.close();} catch (IOException e) {e.printStackTrace();
}
}
}
注意:上述代碼假設 Excel 文件的擴展名為.xlsx。如果 Excel 文件的擴展名為.xls,需要使用 HSSFWorkbook
代替XSSFWorkbook
。
丸趣 TV 網 – 提供最優質的資源集合!
正文完