ExcelのA1形式座標とR1C1形式座標を変換する処理をJSで書いた。
あまり必要になる事は無いと思うが、何となく気になったので。
フォームまで組み上げた物: A1・R1C1相互変換
以下変換部のコード
const A1ToR1C1 = (address) => { address = address.trim().toLowerCase(); const match = /^\$?(?<col>[a-z]+)\$?(?<row>\d+)$/.exec(address); if (!match) { return ""; } let colNum = 0; let digits = 0; for (let c of match.groups.col.split("").reverse()) { colNum += (c.charCodeAt(0) - "a".charCodeAt(0) + 1) * Math.pow(26, digits); digits++; } return `R${match.groups.row}C${colNum}`; }; const R1C1ToA1 = (address) => { address = address.trim(); const match = /^R(?<row>\d+)C(?<col>\d+)$/i.exec(address); if (!match) { return ""; } let colStr = ""; let colNum = +match.groups.col; for (let digit = 0; colNum > 0; digit++) { let thisDigit = colNum % Math.pow(26, digit + 1) / Math.pow(26, digit); if (thisDigit === 0) { thisDigit = 26; // 1スタートだから0にはならない } colNum -= thisDigit * Math.pow(26, digit); colStr = String.fromCharCode("a".charCodeAt(0) + thisDigit - 1).toUpperCase() + colStr; } return `${colStr}${match.groups.row}`; };
通常のN進数表記と異なる点があり、若干釈然としない所も有るのだが、一通りのテストは通るので良しとした。