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) {
String excelFilePath = "example.xlsx";
FileInputStream inputStream = null;
try {
// 创建文件输入流
inputStream = new FileInputStream(new File(excelFilePath));
// 创建工作簿对象
Workbook workbook = new XSSFWorkbook(inputStream);
// 获取第一个工作表
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:
if (DateUtil.isCellDateFormatted(cell)) {
System.out.print(cell.getDateCellValue() + "\t");
} else {
System.out.print(cell.getNumericCellValue() + "\t");
}
break;
case BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t");
break;
case FORMULA:
System.out.print(cell.getCellFormula() + "\t");
break;
default:
System.out.print("未知类型\t");
break;
}
}
System.out.println();
}
// 关闭工作簿
workbook.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
导入依赖:使用 org.apache.poi 库来处理 Excel 文件。确保你已经在项目中添加了 Apache POI 的依赖。
创建文件输入流:通过 FileInputStream 打开 Excel 文件。
创建工作簿对象:使用 XSSFWorkbook 类创建一个工作簿对象,表示整个 Excel 文件。
获取工作表:通过 workbook.getSheetAt(0) 获取第一个工作表。
遍历行和单元格:使用嵌套的 for 循环遍历每一行和每一行中的每个单元格。
读取单元格内容:根据单元格的类型(字符串、数字、布尔值、公式等)读取并打印其内容。
关闭资源:在操作完成后,确保关闭工作簿和文件输入流以释放资源。
.xls 文件而不是 .xlsx 文件,请使用 HSSFWorkbook 而不是 XSSFWorkbook。上一篇:java引用
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站