在 Excel 中,第一列的列名为 A,第二列为 B
第 26 列为 Z,第 27 列为 AA,第 702 列为 ZZ,第703 列为 AAA
以此类推,26个英文字母循环累加计数
有时候我们需要在列的顺序和列名之间相互转换,就需要设计一套算法实现这个功能
这套算法的本质就是一种进制转换,实现代码如下:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <math.h> #define uint32 unsigned int #define astr char* uint32 Excel_GetFieldIndex(astr sText) { uint32 iRet = 0; uint32 iSize = strlen(sText); for ( uint32 i = 0; i < iSize; i++ ) { uint32 iDigit = toupper(sText[i]) - 'A' + 1; uint32 iWeight = pow(26, iSize - i - 1); iRet += iDigit * iWeight; } return iRet; } astr Excel_GetFieldTitle(uint32 iIndex) { uint32 iRem; uint32 arrDigit[7]; uint32 iSize = 0; while ( iIndex ) { iRem = iIndex % 26; if ( iRem == 0 ) { iRem = 26; } iIndex = (iIndex - iRem) / 26; arrDigit[iSize++] = iRem; } astr sRet = (astr)malloc(iSize + 1); for ( uint32 i = 0; i < iSize; i++ ) { sRet[i] = arrDigit[(iSize - i) - 1] + 'A' - 1; } sRet[iSize] = 0; return sRet; } int main() { printf("A : %d\n", Excel_GetFieldIndex("A")); printf("Z : %d\n", Excel_GetFieldIndex("Z")); printf("AA : %d\n", Excel_GetFieldIndex("AA")); printf("ZZ : %d\n", Excel_GetFieldIndex("ZZ")); printf("AAA : %d\n", Excel_GetFieldIndex("AAA")); printf("XFD : %d\n", Excel_GetFieldIndex("XFD")); printf("ZZZ : %d\n", Excel_GetFieldIndex("ZZZ")); printf("AAAA : %d\n", Excel_GetFieldIndex("AAAA")); printf("MWLQKWU : %u\n", Excel_GetFieldIndex("MWLQKWU")); printf("1 : %s\n", Excel_GetFieldTitle(1)); printf("26 : %s\n", Excel_GetFieldTitle(26)); printf("27 : %s\n", Excel_GetFieldTitle(27)); printf("702 : %s\n", Excel_GetFieldTitle(702)); printf("703 : %s\n", Excel_GetFieldTitle(703)); printf("16384 : %s\n", Excel_GetFieldTitle(16384)); printf("18278 : %s\n", Excel_GetFieldTitle(18278)); printf("18279 : %s\n", Excel_GetFieldTitle(18279)); printf("4294967295 : %s\n", Excel_GetFieldTitle(4294967295)); return 0; }