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 {
// 创建文件输入流
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");
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 文件。XSSFWorkbook
用于读取 .xlsx
格式的文件。excelFilePath
是你 Excel 文件的路径,需要根据实际情况修改。FileInputStream
打开 Excel 文件。XSSFWorkbook
类读取 Excel 文件,并获取第一个工作表。for
循环遍历每一行和每一个单元格。如果你没有安装 Apache POI 库,可以通过 Maven 或手动下载并添加到项目中。
上一篇:java解析json格式的文件
下一篇:java 浮点数
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站