Java可以通過使用Apache POI庫來讀取本地Excel文件。以下是一個簡單的示例代碼:
import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class ExcelReader {
public static void main(String[] args) {
try {
FileInputStream file = new FileInputStream("example.xlsx");
Workbook workbook = WorkbookFactory.create(file);
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
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();
}
file.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
在這個示例中,我們首先創(chuàng)建一個FileInputStream
對象,指定要讀取的Excel文件的路徑。然后使用WorkbookFactory
類的create
方法創(chuàng)建一個Workbook
對象,再從中獲取第一個Sheet。接著我們遍歷Sheet中的每一行和每一個單元格,并根據(jù)單元格的類型來讀取相應的值。最后,關閉文件流。
請注意,你需要包含Apache POI庫的相關依賴,例如在Maven項目中添加以下依賴:
<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>
這樣就可以使用Java讀取本地Excel文件了。