使用 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

相关推荐
whale fall1 小时前
celery -A tool.src.main worker --loglevel=info --queues=worker1_queue & 什么意思
python·学习·apache
TracyCoder12312 小时前
ElasticSearch核心引擎Apache Lucene(五):相关性算分 (Scoring)
elasticsearch·apache·lucene
码上上班12 小时前
一文学会apache httpd
apache
野生技术架构师12 小时前
Spring Boot 3 集成 Apache Calcite:多数据源查询的终极解决方案
spring boot·后端·apache
TracyCoder1231 天前
ElasticSearch核心引擎Apache Lucene(四):段 (Segment) 的设计与合并
elasticsearch·apache·lucene
TracyCoder1231 天前
ElasticSearch核心引擎Apache Lucene(三):数值与空间数据索引
elasticsearch·apache·lucene
Elastic 中国社区官方博客1 天前
Elasticsearch:Apache Lucene 2025 年终总结
大数据·人工智能·elasticsearch·搜索引擎·apache·lucene
TracyCoder1232 天前
ElasticSearch核心引擎Apache Lucene(二):正排索引的奥秘
elasticsearch·apache·lucene
TracyCoder1232 天前
ElasticSearch核心引擎Apache Lucene(一):倒排索引底层实现
elasticsearch·apache·lucene
麦兜*2 天前
深入解析云原生时代的高性能消息中间件:基于Apache Pulsar与Kafka架构对比的万亿级数据吞吐与低延迟实时处理实战
云原生·kafka·apache