Column index to Excel A1 notation Converter
Version 1.0.0 (1.75 KB) by
滨江
这是一个Matlab的函数,用于将任意正整数(列序号)转换为Excel的A1样式。 Convert positive integer (idx) to Excel A1 notation without limit of max index.
This function converts an index of column to the Excel A1 notation. But there is no limit to the maximal index.
%%%
function A1string = idx2A1(idx)
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
if idx >= 1
n = ceil((log(idx*25/26+1))/log(26))-1; %求取小于索引idx的最大n值,n是求和Sn的指标,其中Sn=26+26^2+...+26^n。这步等同于求取A1样式的字符数量
idxr = idx-(26/25*(26^n-1)); %这步等同于求(idx-Sn)
A1by26th = dec2base(idxr-1,26,n+1)'; % 将索引的余idxr转换为26进制数(char类型数据),转置得到字符列向量。idxr要-1是因为本来例如AAAA的样式代表0000,但实际上这是第1列
A1by26th = base2dec(A1by26th,26)'; % 将转置的26进制数转换回索引idx
%%% 转置的这两步是为了将索引数idx的27进制数按位分开(将char字符转置后进行进制转换即可将字符从字符行向量变成数值列向量) %%%
A1by26th = A1by26th+1; %用26进制表示后,0对应A,但定义的字母表字符向量是从1开始计数的,所以26进制数组要整体+1才能对上
A1string = alphabet(A1by26th); % 将A1对应的数值行向量带入字符行向量,则可取出一个字符向量,其中的列与数值向量的列一一对应
else
end
%%%
该代码的实现可以如下理解:
首先将A1样式作如下排列,
[ A B C ... X Y Z ] = M = M1
[ AA AB AC ... AX AY AZ;
BA BB BC ... BX BY BZ; = M1+M' = M2
... ... ... ... ... ... ...
ZA ZB ZC ... ZX ZY ZZ ]
[ AAA AAB AAC ... AAX AAY AAZ;
... ... ... ... ... ... ...
AZA AZB AZC ... AZX AZY AZZ; = M2+M' = M3
...
ZZA ZZB ZZC ... ZZX ZZY ZZZ ]
...
要找到列序号(idx)对应的A1样式,可以分为两步:首先找到idx在哪个矩阵(Mn)中;然后找到列序号的余数(idxr)在Mn中代表的字符。
可以看出Mn的元素数目为26^n,则前n个M的元素总数Sn=26*(26^n-1)/25,可以据此首先判断idx位于哪个Mn中。
idxr对应所求样式在Mn中的序号,而所求样式在Mn中的位置可以通过26进制判断。由于Mn矩阵第一个元素对应00...01而不是00...00,如M3中的第一个元素'AAA'对应001而不是000,所以要用(idxr-1)对应的26进制数去确定所求样式的位置。
另外由于'A'在26进制对应0,'B'在26进制对应1,...,'Z'在26进制对应25,而字符向量的索引是从1开始的,所以求出的26进制数要在所有位数上+1才能对应上字符向量的索引。
Cite As
滨江 (2025). Column index to Excel A1 notation Converter (https://www.mathworks.com/matlabcentral/fileexchange/181028-column-index-to-excel-a1-notation-converter), MATLAB Central File Exchange. Retrieved .
MATLAB Release Compatibility
Created with
R2024b
Compatible with any release
Platform Compatibility
Windows macOS LinuxTags
Acknowledgements
Inspired by: Convert index to Excel A1 notation
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!Discover Live Editor
Create scripts with code, output, and formatted text in a single executable document.
| Version | Published | Release Notes | |
|---|---|---|---|
| 1.0.0 |
