Java使用Apache POI读取Excel文件

一、下载jar包

Apache POI有提供下载地址:Apache Archive Distribution Directory,直接打开链接并选择所需的版本下载即可(双击last modified可按最新更新时间排序),本文章以poi-bin-4.1.1-20191023.zip 为例,进入官网下载链接后,点击如下图红框所示的蓝色链接即可下载,也可以点击此链接直接获取;

二、导入jar包

打开eclipse,创建项目,在项目下创建一个空文件夹poi;

poi-bin-4.1.1-20191023.zip解压 后的jar包导入到poi中;

并将导入的jar包Add to Build Path ;

三、创建代码

先在D盘创建测试Excel文件,在Excel中输入以下数据并命名为demo:

在eclipse创建的项目中创建ExcelReader 类;

添加以下代码并运行:

bash 复制代码
package com.Excel;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.DataFormatter;

import java.io.File;
import java.io.IOException;

public class ExcelReader {

	public static void main(String[] args) {
		String filePath = "D:\\demo.xlsx"; // 替换为你的 Excel 文件路径

		try {
			// 加载 Excel 文件
			Workbook workbook = WorkbookFactory.create(new File(filePath));
			// 获取第一个工作表
			Sheet sheet = workbook.getSheetAt(0);

			// 遍历每一行
			for (Row row : sheet) {
				// 遍历每一列
				for (Cell cell : row) {
					// 使用 DataFormatter 格式化单元格内容
					DataFormatter formatter = new DataFormatter();
					String cellValue = formatter.formatCellValue(cell);
					System.out.print(cellValue + "\t");
				}
				System.out.println();
			}

			// 关闭工作簿
			workbook.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

以下为输出结果,输出结果与excel文件中的数据一致,至此,成功使用了apache poi读取excel文档!

bash 复制代码
姓名	年龄	
张三	20	
李四	25