http://jsfiddle.net/easywaru/8euvLuha/
Excel:A1 <-> Coord:(1,1)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
// 0 | 1 case 0: (0,0) -> A1 case 1: (1,1) -> A1 var coordinationIndexBase = 1; var reRow = new RegExp("(\\d+)$"); var reCol = new RegExp("^([A-Z]+)"); var getRowName = function(cellName) { var found = cellName.match(reRow); if(!found){ throw new Error("Parameter \"cellName\" has no convertable row name. cellName = " + cellName + ""); } return found[0]; }; var getColName = function(cellName) { var found = cellName.match(reCol); if(!found){ throw new Error("Parameter \"cellName\" has no convertable column name. cellName = " + cellName + ""); } return found[0]; }; var getRowIndex= function(cellName) { var rowIndex = parseInt(getRowName(cellName)); rowIndex -= 1 - coordinationIndexBase; return rowIndex; }; var getColIndex = function(cellName){ var colName = getColName(cellName); var colIndex = 0; for (var i = 0, iLen = colName.length; i < iLen ; i++) { colIndex *= 26; colIndex += alpha2number(colName[i]) + 1; } colIndex -= 1 - coordinationIndexBase; return colIndex; }; var getCellName = function(rowIndex , colIndex){ if(rowIndex < coordinationIndexBase){ throw new Error("Parameter \"rowIndex\" can't less then "+coordinationIndexBase +". rowIndex = " + rowIndex + ""); } if(colIndex < coordinationIndexBase){ throw new Error("Parameter \"colIndex\" can't less then "+coordinationIndexBase +". colIndex = " + colIndex + ""); } rowIndex -= coordinationIndexBase - 1; colIndex -= coordinationIndexBase - 1; var colName = ''; while (true) { colIndex -= 1 colName = number2alpha(colIndex % 26) + colName; colIndex = Math.floor(colIndex / 26); if (colIndex <= 0) { break; } } return cellName = colName + rowIndex; } // A -> 0 var alpha2number = function(alpha) { var number = alpha.charCodeAt(0) - 65; return number; } // 0 -> A var number2alpha = function(number) { if (number < 0) { return ""; } var alpha = String.fromCharCode(65 + number); return alpha; } |