当前位置: 首页 > news >正文

Java 和 Apache POI 处理 Excel 文件

一、引言

在企业应用中,Excel 是一种常见的数据存储和交换格式。Java 通过 Apache POI 库可以高效地读取、修改和写入 Excel 文件。本文介绍如何使用 Java 处理 Excel 文件,包括读取、写入和修改数据。

二、环境准备
2.1 安装 Java 开发环境

下载并安装 Java SDK:Oracle JDK 下载

验证安装:

java -version

2.2 添加 Maven 依赖

在 pom.xml 中添加 Apache POI 依赖:

org.apache.poipoi-ooxml5.2.3

三、代码实现
3.1 读取 Excel 文件

以下示例代码演示如何读取 Excel 文件的内容:

package com.example;

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 ReadExcel {

public static void main(String[] args) {String filePath = "data.xlsx"; // Excel 文件路径try (FileInputStream fis = new FileInputStream(new File(filePath));Workbook workbook = new XSSFWorkbook(fis)) {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;default:System.out.print("未知类型\t");}}System.out.println();}} catch (IOException e) {e.printStackTrace();}
}

}

运行结果(示例 Excel 文件):

姓名 年龄 成绩
张三 23 85.5
李四 25 90.2

3.2 写入 Excel 文件

以下示例代码演示如何创建并写入 Excel 文件:

package com.example;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

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

public class WriteExcel {

public static void main(String[] args) {Workbook workbook = new XSSFWorkbook();Sheet sheet = workbook.createSheet("学生成绩");// 创建表头Row headerRow = sheet.createRow(0);headerRow.createCell(0).setCellValue("姓名");headerRow.createCell(1).setCellValue("年龄");headerRow.createCell(2).setCellValue("成绩");// 添加数据Object[][] data = {{"张三", 23, 85.5},{"李四", 25, 90.2}};int rowNum = 1;for (Object[] rowData : data) {Row row = sheet.createRow(rowNum++);for (int i = 0; i < rowData.length; i++) {if (rowData[i] instanceof String) {row.createCell(i).setCellValue((String) rowData[i]);} else if (rowData[i] instanceof Integer) {row.createCell(i).setCellValue((Integer) rowData[i]);} else if (rowData[i] instanceof Double) {row.createCell(i).setCellValue((Double) rowData[i]);}}}// 保存 Excel 文件try (FileOutputStream fos = new FileOutputStream(new File("output.xlsx"))) {workbook.write(fos);System.out.println("Excel 文件写入成功!");} catch (IOException e) {e.printStackTrace();}try {workbook.close();} catch (IOException e) {e.printStackTrace();}
}

}

运行结果:生成 output.xlsx 文件,包含以下数据:

姓名 年龄 成绩
张三 23 85.5
李四 25 90.2

3.3 修改 Excel 文件

以下示例代码演示如何修改 Excel 文件中的数据:

package com.example;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;

public class ModifyExcel {

public static void main(String[] args) {String filePath = "output.xlsx";try (FileInputStream fis = new FileInputStream(new File(filePath));Workbook workbook = new XSSFWorkbook(fis)) {Sheet sheet = workbook.getSheetAt(0);// 修改第一行第二列的数据Row row = sheet.getRow(1);if (row != null) {Cell cell = row.getCell(2);if (cell != null) {cell.setCellValue(95.0); // 修改成绩}}// 保存修改后的 Excel 文件try (FileOutputStream fos = new FileOutputStream(new File(filePath))) {workbook.write(fos);System.out.println("Excel 文件修改成功!");}} catch (IOException e) {e.printStackTrace();}
}

}

运行结果:output.xlsx 文件中 张三 的成绩被修改为 95.0。

四、优化与扩展

支持 CSV 读取:扩展程序支持 CSV 格式文件的读取和写入。

批量处理数据:支持从数据库读取数据并写入 Excel。

格式化 Excel:使用 Apache POI 提供的 CellStyle 进行单元格格式化,如字体加粗、颜色填充等。

http://www.rkmt.cn/news/55691.html

相关文章:

  • 有志青年
  • python舆情分析可视化平台 情感分析 微博 爬虫 scrapy爬虫手艺 朴素贝叶斯分类算法大数据 计算机✅
  • Python thread lambda run multiple functions
  • csp-s 2025 随笔
  • 内网穿透配置和使用 - Rainbow
  • 13. Spring AI 的观测性 - Rainbow
  • Elasticsearch8.4.1升级Elasticsearch9.1.5 - 实践
  • 工具成瘾——黑客为何痴迷工具与AI(及如何开始用脑思考)
  • 完整教程:Flask入门教程——李辉 第5章: 数据库 关键知识梳理
  • SLB及健康检查
  • 2025牛客国庆集训派对day7 M C 个人题解 - 教程
  • C++ 中 struct 与 class 的用法与区别
  • 07.创建型 - 抽象工厂模式(Abstract Factory Pattern)
  • 模型量化原理
  • 日总结 29
  • 2025.11.19 C 题解
  • 2025.11.20
  • 【比赛记录】2025CSP+NOIP 冲刺模拟赛合集Ⅵ
  • 3 分钟上手 SightAI:在你熟悉的工具里直接调用顶级大模型 - sight
  • 2025.11.20博客
  • 芯谷科技--高性能电动工具直流调速电路GS069 - 指南
  • 洛谷 B4411:[GESP202509 二级] 优美的数字 ← 嵌套循环
  • 2025 门窗十大品牌精准选购指南:行业评估报告 + 白皮书护航,选窗不踩坑!
  • 网络流建模
  • 2025 门窗十大品牌权威榜单:依托行业评估报告 + 选购白皮书,省心采购指南!
  • 安卓中执行 root 命令
  • UniApp缓存系统详解 - 详解
  • CF2165 VP 记录
  • 如何在SPM混编中实现不同target之间的通信?
  • 专题:2025构建全自动驾驶汽车生态系统:中国智能驾驶行业全景研究报告|附80+份报告PDF、数据仪表盘汇总下载