要在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
。