获取类似excel的列名的Javascript算法

Javascript Algorithm to get the excel-like column name

本文关键字:Javascript 算法 获取 excel      更新时间:2023-09-26

基本上我想做的是创建一个字符列表,格式类似excel列名。

的例子:a, b, c, d,…,z, aa、ab, ac,…,yz

在PHP中你可以循环使用下面的代码:

for($char = "A"; $char <= "Z"; $char++) 
{
    echo $char . "'n";
}

但是当我在javascript中尝试时:

 var i3;
 var text3 = "";
for(i3 = "A"; i3 <= "Z"; i3++)
{
    text3 += i3 + ", ";
}
document.getElementById("pId").innerHTML = text3;

这对我不起作用。我的代码有错误吗?或者PHP逻辑在JS中不起作用?如果你知道如何制作,请告诉我,谢谢。

在javascript中,当对字符串值调用递增运算符时,将返回NaN

您可以使用基于ascii码的实现,如

var i3, i4;
var text3 = "";
for (i3 = 0; i3 < 26; i3++) {
  text3 += String.fromCharCode(97 + i3) + ", ";
}
for (i3 = 0; i3 < 26; i3++) {
  for (i4 = 0; i4 < 26; i4++) {
    text3 += String.fromCharCode(97 + i3) + String.fromCharCode(97 + i4) + ", ";
  }
}
document.getElementById("pId").innerHTML = text3;
<span id="pId"></span>

短就是美!

var nextChar = c=>c?String.fromCharCode(c.charCodeAt(0)+1):'A';
var nextCol = s=>s.replace(/([^Z]?)(Z*)$/, (_,a,z)=>nextChar(a) + z.replace(/Z/g,'A'));
//test:
nextCol(''); //A
nextCol('A'); //B
nextCol('Z'); //AA
nextCol('AA'); //AB
nextCol('XYZ'); //XZA
nextCol('ZZZZ'); //AAAAA
//output: A,B,C,...,ZZ
for(var i=0, s=''; i<702; i++){
    s = nextCol(s);
    console.log(s);
}
//output: A,B,C,...,ZZZZ
for(var i=0, s=''; i<475254; i++){
    s = nextCol(s);
    console.log(s);
}

我编写了一个名为next的函数,它提供相邻的右单元格。

function next(currentCell) {
    let regex = /[A-Z]/g;
    let numberRegex = /[0-9]/g;
    let chars = currentCell.match(regex);
    let nums = currentCell.match(numberRegex);
    let flag = true;
    let x = 1;
    while (flag) {
        if (chars[chars.length - x] === 'Z') {
            if ((chars.length - x) === 0) {
                chars[chars.length - x] = 'A';
                chars.unshift('A');
                flag = false;
            } else {
                chars[chars.length - x] = 'A';
                x++;
            }
        } else {
            chars[chars.length - x] = String.fromCharCode(chars[chars.length - x].charCodeAt(0) + 1);
            flag = false;
        }
    }
    return chars.join("") + nums.join("");
}
next('A1') // returns 'B1'
next('ZZ90') // returns 'AAA90'

请尝试下面的代码来完成javascript

var i3;
var text3 = "";
var c;
   for(i3 = 65; 90 >= i3; i3++)
{
    c = String.fromCharCode(i3);
    text3 += c + ", ";
}
document.getElementById("pId").innerHTML = text3;