Get the Column Index of a Cell in Excel using OpenXML C#

前端 未结 8 1839
北恋
北恋 2020-12-03 17:32

I\'ve been looking around for a while now and cannot seem to find out how to do this. I\'ve got an excel sheet, which I\'m reading using OpenXML. Now the normal thing would

8条回答
  •  醉话见心
    2020-12-03 18:02

        [TestCase( 1, 0, "A1" )]
        [TestCase( 2, 25, "Z2" )]
        [TestCase( 2, 38, "AM2" )]
        [TestCase( 2, (26 * 4) + 1, "DB2" )]
        [TestCase( 2, (26 * 26 * 26 * 18) + (26 * 26 * 1) + (26 * 26 * 1) + ( 26 * 1 ) + 2, "RBAC2" )]
        public void CanGetCorrectCellReference( int row, int column, string expected )
            => GetCellReference( (uint)row, (uint)column ).Value.ShouldEqual( expected );
    
        public static StringValue GetCellReference( uint row, uint column ) =>
            new StringValue($"{GetColumnName("",column)}{row}");
    
        static string GetColumnName( string prefix, uint column ) => 
            column < 26 ? $"{prefix}{(char)( 65 + column)}" : 
            GetColumnName( GetColumnName( prefix, ( column - column % 26 ) / 26 - 1 ), column % 26 );
    

提交回复
热议问题