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

在JavaScript中将二维数组索引转换为电子表格单元格坐标

将二维数组索引(CSV格式)转换为电子表格单元格坐标(JavaScript实现)

核心逻辑拆解

要实现这个转换,分三步走:

  • 解析CSV输入:把类似"0, 0"的字符串拆成两个0起始的数字(行索引、列索引)
  • 列索引转字母:把数字转换成A-Z/AA-AZ这类电子表格列名
  • 行索引转行号:把0起始的行索引加1,得到电子表格的1起始行号

具体实现代码

列索引转字母工具函数

电子表格列名是特殊的26进制(无0位,A对应1、Z对应26、AA对应27),所以转换时需要做适配:

function numberToColumnLetter(num) {
  let letter = '';
  while (num >= 0) {
    const remainder = num % 26;
    letter = String.fromCharCode(65 + remainder) + letter;
    num = Math.floor(num / 26) - 1; // 抵消无0位的差异
  }
  return letter;
}

完整转换函数

整合解析、转换、拼接逻辑,同时处理输入合法性:

function indexToCell(csvIndex) {
  // 拆分并清理输入,兼容带空格的情况
  const [rowStr, colStr] = csvIndex.split(',').map(s => s.trim());
  const rowIndex = parseInt(rowStr, 10);
  const colIndex = parseInt(colStr, 10);

  // 拦截非法输入
  if (isNaN(rowIndex) || isNaN(colIndex) || rowIndex < 0 || colIndex < 0) {
    throw new Error('请输入格式合法的非负整数对,例如"0, 0"');
  }

  const columnLetter = numberToColumnLetter(colIndex);
  const rowNumber = rowIndex + 1; // 转成1起始的行号

  return `${columnLetter}${rowNumber}`;
}

测试示例

console.log(indexToCell("0, 0")); // 输出:"A1"
console.log(indexToCell("3, 4")); // 输出:"D5"
console.log(indexToCell("10, 26")); // 输出:"AA11"
console.log(indexToCell("5, 51")); // 输出:"AZ6"

补充说明

  • 输入中的多余空格会被自动清理,比如" 2 , 7 "这类格式也能正常处理
  • 若不需要非法输入拦截,可移除对应的判断逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 17:55:57