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 = "path/to/your/excel/file.xlsx";
FileInputStream inputStream = null;
try {
// 创建文件输入流,用于读取Excel文件
inputStream = new FileInputStream(new File(excelFilePath));
// 使用XSSFWorkbook类来读取.xlsx格式的Excel文件
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");
}
}
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文件。poi-ooxml
库用于处理.xlsx
格式的文件。FileInputStream
读取Excel文件。XSSFWorkbook
类来读取.xlsx
格式的Excel文件。workbook.getSheetAt(0)
获取第一个工作表。for-each
循环遍历每一行和每一列,根据单元格的类型(字符串、数字、布尔值等)读取并打印内容。Workbook
和FileInputStream
以释放资源。请确保你已经在项目中添加了Apache POI库的依赖,例如通过Maven:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
上一篇:java map 按key排序
下一篇:java 比较时间大小
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站