使用 Apache POI 更新/覆盖 特定的单元格

使用 Apache POI 更新特定的单元格

  • [一. 需求](#一. 需求)
  • [二. 实现](#二. 实现)
  • [三. 效果](#三. 效果)

一. 需求

将以下表中第4行,第4列的单元格由"张宇"更新为"汤家凤",并将更行后的结果写入新的Excel文件中;

二. 实现

使用Apache POI,可以精确定位到需要更改的单元格!高定制化的场景有时可能不适合用easyExcel;

步骤:

  • 由 file 依次 获取 workbook、sheet、row、cell;
  • 更新 cell;
  • 关闭 输入流,用新文件的path创建输出流;
  • 将更改后的 workbook 通过输出流 写入 新文件;
  • 关闭 workbook和输出流。
java 复制代码
import org.apache.poi.xssf.usermodel.*;
import org.junit.Test;
import java.io.*;

public class poiTest {
    @Test
    public void update() throws Exception{
        String sourceFile = "C:\\Users\\liziq\\Desktop\\student.xlsx"; // 原文件
        String newFile = "C:\\Users\\liziq\\Desktop\\student-new.xlsx"; // 更新后的新文件
        // 创建输入流
        FileInputStream fileInputStream = new FileInputStream(sourceFile);
        // 获取 workbook
        XSSFWorkbook wb = new XSSFWorkbook(fileInputStream);
        // 获取 sheet
        XSSFSheet sheet = wb.getSheetAt(0);
        // 获取单元格(index是从0开始)
        XSSFRow row = sheet.getRow(3);
        XSSFCell cell = row.getCell(3);
        // 更新单元格
        cell.setCellValue("汤家凤");
        // 关闭输入流
        fileInputStream.close();
        // 创建输出流
        FileOutputStream fileOutputStream=new FileOutputStream(newFile);
        // 将 workbook 写入 newFile
        wb.write(fileOutputStream);
        // 关闭workbook和输出流
        wb.close();
        fileOutputStream.close();
    }
}

三. 效果

生成"student-new.xlsx",教高数的变成了"汤家凤"!

参考:

https://blog.csdn.net/zouxiongqqq/article/details/78478298

相关推荐
阿絮~4 分钟前
Apache RocketMQ进阶之路阅读笔记和疑问
笔记·apache·rocketmq
Fireworkitte2 天前
Apache POI 详解 - Java 操作 Excel/Word/PPT
java·apache·excel
蚂蚁数据AntData2 天前
从性能优化赛到社区Committer,走进赵宇捷在Apache Fory的成长之路
大数据·开源·apache·数据库架构
小湘西2 天前
Apache HttpClient 的请求模型和 I/O 类型
java·http·apache
超级小忍13 天前
Spring Boot 集成 Apache Kafka 实战指南
spring boot·kafka·apache
天上掉下来个程小白15 天前
Apache ECharts-02.入门案例
前端·spring boot·apache·echarts·苍穹外卖
SelectDB技术团队15 天前
Apache Doris 3.0.6 版本正式发布
大数据·数据分析·apache·实时分析·极速分析
guygg8816 天前
Linux中的阻塞信号与信号原理
linux·mysql·apache
天上掉下来个程小白17 天前
Apache ECharts-01.介绍
前端·javascript·spring boot·apache·苍穹外卖