You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Apache POI如何计算空单元格的单元格地址?

Apache POI 计算空单元格地址实现

场景说明

现有一份Excel表格内容如下:

A B C D
1 x x x x
2 x x   x
3 x x x x

遍历某一行的列时,使用如下Kotlin代码:

for (i in 0 until lastCellNum) {
    val cell = row.getCell(i)
    if (cell != null){
        println(cell.address)
    } else {
        println("cell data is missing at address: "+ //address_calculation)
    }    
}

需求是遇到空单元格(如示例中的C2)时,输出cell data is missing at address: C2,需要实现空单元格的地址计算。

实现方法

要生成空单元格的地址,需完成两部分计算:列索引转Excel列名,以及获取Excel行号。

1. 列索引转列名工具函数

Excel列名采用A-Z、AA-AZ的26进制变种规则,实现函数将0开始的列索引转换为对应列名:

fun getColumnName(columnIndex: Int): String {
    val sb = StringBuilder()
    var index = columnIndex
    while (index >= 0) {
        val remainder = index % 26
        sb.append((('A'.toInt() + remainder).toChar()))
        index = (index / 26) - 1
    }
    return sb.reverse().toString()
}

2. 修改后的遍历代码

将工具函数整合到原遍历逻辑中,即可输出正确的空单元格地址:

// 列索引转列名函数
fun getColumnName(columnIndex: Int): String {
    val sb = StringBuilder()
    var index = columnIndex
    while (index >= 0) {
        val remainder = index % 26
        sb.append((('A'.toInt() + remainder).toChar()))
        index = (index / 26) - 1
    }
    return sb.reverse().toString()
}

// 遍历行的核心逻辑
for (i in 0 until row.lastCellNum) {
    val cell = row.getCell(i)
    if (cell != null){
        println(cell.address)
    } else {
        val columnName = getColumnName(i)
        val rowNumber = row.rowNum + 1 // POI行索引从0开始,需加1对应Excel行号
        println("cell data is missing at address: $columnName$rowNumber")
    }    
}

关键说明

  • getColumnName(i):将循环中的列索引i(0对应A,1对应B,2对应C)转换为Excel标准列名。
  • row.rowNum + 1:POI中rowNum是从0起始的索引,加1后得到Excel界面显示的行号。
  • 拼接列名与行号,即可生成如C2格式的单元格地址。

内容的提问来源于stack exchange,提问作者beatrice

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 05:35:10