java代码读取表格中数据
时间: 2023-09-17 14:01:34 浏览: 114
Java代码可以使用Apache POI库来读取表格中的数据。下面是一个简单的示例:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.*;
public class ExcelReader {
public static void main(String[] args) {
try {
// 打开表格文件
FileInputStream file = new FileInputStream(new File("path/to/your/excel/file.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 (IOException e) {
e.printStackTrace();
}
}
}
```
在以上示例中,首先我们使用`FileInputStream`来读取Excel文件。然后创建`Workbook`对象,通过`WorkbookFactory.create()`方法来读取工作簿中的数据。
然后,我们选择第一个工作表,通过遍历每一行来读取表格中的数据。对于每个单元格,根据单元格的类型使用`getCellType()`方法来判断数据类型,然后使用对应的方法(例如`getStringCellValue()`、`getNumericCellValue()`、`getBooleanCellValue()`)来读取数据。
最后,记得关闭文件流以释放资源。请注意,你需要根据你的实际需求和文件路径来修改代码中的文件路径。
阅读全文
相关推荐


















