溫馨提示×

java如何讀取excel表數(shù)據(jù)

小億
95
2023-09-22 11:34:41
欄目: 編程語言

在Java中讀取Excel表的數(shù)據(jù),可以使用Apache POI庫來實現(xiàn)。Apache POI是一個流行的Java庫,用于讀寫Microsoft Office文件,包括Excel文件。

以下是一個簡單的示例代碼,演示如何使用Apache POI來讀取Excel表的數(shù)據(jù):

import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.*;
public class ExcelReader {
public static void main(String[] args) {
try {
// 打開Excel文件
FileInputStream fis = new FileInputStream("path/to/excel.xlsx");
// 創(chuàng)建工作簿對象
Workbook workbook = WorkbookFactory.create(fis);
// 獲取第一個工作表
Sheet sheet = workbook.getSheetAt(0);
// 遍歷工作表的每一行
for (Row row : sheet) {
// 遍歷行的每一列
for (Cell cell : row) {
// 根據(jù)單元格的類型讀取數(shù)據(jù)
switch (cell.getCellType()) {
case STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
case NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t");
break;
default:
System.out.print("\t");
}
}
System.out.println();
}
// 關(guān)閉文件流
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

請注意,在上述代碼中,你需要修改"path/to/excel.xlsx"為實際的Excel文件路徑。此外,代碼中假設(shè)第一個工作表是要讀取的工作表。如果需要讀取其他工作表,可以使用workbook.getSheetAt(index)方法來獲取對應(yīng)的工作表,其中index表示工作表的索引,從0開始計數(shù)。

另外,需要在項目中引入Apache POI庫的相關(guān)依賴,可以通過Maven或Gradle等構(gòu)建工具來完成。具體的依賴配置可以參考Apache POI官方文檔。

0