要在Java中獲取Excel數據,可以使用Apache POI庫。以下是獲取Excel數據的基本步驟:
<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
。