在 Power Query 中将数字转换为 Excel 列字母

Convert numbers to Excel Column Letters in Power Query

我想将数字转换为 Excel 列字母。

这个话题有好几个帖子,但是好像还没有M语言的回答。

我设法用以下代码解决了这个问题,但我相信有人会提出更有效的代码:

= Table.AddColumn(Source, "Column Letter", each Text.Combine({ if (Number.IntegerDivide(
    Number.IntegerDivide(
        Number.IntegerDivide([Column1]-1,1),26)-1,26))<1 then "" else Character.FromNumber( 64+Number.IntegerDivide(Number.IntegerDivide(Number.IntegerDivide([Column1]-1,1),26)-1,26)),
(if Number.IntegerDivide([Column1]-1,26)-
Number.Abs(
    Number.IntegerDivide(
        Number.IntegerDivide([Column1]-1,26)
        -1,26)*26)<1 then "" else 
        Character.FromNumber(64+
        Number.IntegerDivide([Column1]-1,26)-Number.Abs(
            Number.IntegerDivide(
                Number.IntegerDivide([Column1]-1,26)-1,26)*26))),
    (if [Column1]-Number.Abs(
    Number.IntegerDivide([Column1]-1,26)*26)<1 then "" else Character.FromNumber(64+[Column1]-Number.Abs(
    Number.IntegerDivide([Column1]-1,26)*26)))})) 

谢谢!

我认为这个自定义函数也可以工作:

编辑
*b 的公式根据@VassilisAgapitos 下面的注释更正

(n as number)=>

let 
//make sure it is an integer
    a = Number.IntegerDivide(n,1),
    
    b = Number.IntegerDivide(Number.IntegerDivide(a-1,26)-1,26),
    L1 = if b = 0 then null else Character.FromNumber(b+64),

    c = Number.IntegerDivide(a-b*26*26-1,26),
    L2 = if c = 0 then null else Character.FromNumber(c+64),
    
    d = a-b*26*26-c*26,
    L3 = Character.FromNumber(d+64) 
in  
    Text.Combine({L1,L2,L3}) 

您可以将其用作 Table.AddColumn 参数:

 #"Added Custom" = Table.AddColumn(#"Changed Type", "Column Letter", each fnNumberToExcelColumn([Column Number]), type text)

一个比罗恩的更丑的版本,只是为了好玩

=(if [Column1] <703 then "" else Character.FromNumber(64+Number.IntegerDivide([Column1]-27,26*26)))
&( if [Column1] >26 then Replacer.ReplaceText(Character.FromNumber(64+ Number.Mod( Number.IntegerDivide([Column1]-1,26) ,26) ), "@", "Z") else "" )
&(Character.FromNumber(65+Number.Mod([Column1]-1,26)))