read-excel-file
Version:
Read `.xlsx` files in a web browser or in Node.js
39 lines (38 loc) • 1.62 kB
JavaScript
/**
* Parses cell address into a row number and a column number.
* Examples: "A1" → [1,1], "B2" → [2,2], "AA2091" → [2091, 27], "R988" → [988, 18].
* @param {string} cellAddress
* @returns {number[]} Returns `[rowNumber, columnNumber]`
*/
export default function parseCellAddress(cellAddress) {
// const CELL_ADDRESS_LETTERS = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
// Split a cell coordinate into the letter part (left) and numeric part (right).
// Cell coordinate example: "AA2091", "R988", "B1".
var columnNumber = 0;
var i = 0;
while (i < cellAddress.length) {
var charCode = cellAddress.charCodeAt(i);
// `48` is the character code of "0", `57` is the character code of "9".
if (charCode >= 48 && charCode <= 57) {
var rowNumber = Number(cellAddress.slice(i));
if (isNaN(rowNumber)) {
invalidCellAddress(cellAddress);
}
return [
// Row number (starting at `1`).
rowNumber,
// Column number (starting at `1`).
columnNumber];
}
// Convert a letter coordinate to a digit coordinate.
// Examples: "A" -> 1, "B" -> 2, "Z" -> 26, "AA" -> 27, etc.
columnNumber *= 26; // Same as: CELL_ADDRESS_LETTERS.length
columnNumber += cellAddress.charCodeAt(i) - 64; // Same as: CELL_ADDRESS_LETTERS.indexOf(cellAddress[i]) + 1
i++;
}
invalidCellAddress(cellAddress);
}
function invalidCellAddress(cellAddress) {
throw new Error("<c r=\"".concat(cellAddress, "\">"));
}
//# sourceMappingURL=parseCellAddress.js.map