I need to know column name of a spread sheet with a given starting colum upto n number of columns
let say starting column is “AB”, I want to know the column (label) after 99 columns.
For those who need Ralph answer in T-SQL flavor
Create FUNCTION fsExcelValueToColum(@value int) returns varchar(3) as
begin
DECLARE @DIGIT INT,@RV VARCHAR(3);set @rv=''
IF @VALUE=0 RETURN @rv
WHILE @VALUE > 0
BEGIN
SET @DIGIT = @VALUE % 26
IF @DIGIT = 0
BEGIN
set @RV=@RV+'Z'
set @RV=@RV+dbo.fsExcelValueToColum(@value /26 -1)
return @rv
END
set @rv=@rv+char(@digit+64)
set @value=(@value-@digit) /26
END
return @rv
end
USE [ecs]
GO
/****** Object: UserDefinedFunction [dbo].[fnExcelColumnToValue] Script Date: 12/06/2009 10:33:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER function [dbo].[fnExcelColumnToValue](@Column varchar(3)) returns int as
Begin
--declare @column varchar(10); select @column = 'AC'
declare @value int, @pow int,@i int,@n int
select @pow=1,@VALUE=0,@I=LEN(@COLUMN)
SET @I=LEN(@COLUMN)
WHILE @I >= 1
BEGIN
SET @VALUE=@VALUE+@POW*((ASCII(SUBSTRING(UPPER(@COLUMN),@I,1)) - 65) +1)
SET @POW=@POW *26
SET @I=@I-1
END
return @value
end
Think of the characters
A,B, … ,Zas representing the values 1, 2, … 26 (you can’t quite think of this as being base-26 because there is no character representing 0 nor can there be as we don’t want, for example,AAto mean 0). So we have to engage in some trickery to deal with this:So that
outputs
DWandoutputs
Z. Obviously you can wrap this all up in a nice class and make it fluent or what have you.Explanation: Think, for example, of the value 702 and a usual base-26 notation where there is a digit representing 0 (I will use the notation
_to represent this magical digit so that we don’t get confused between the value 0 and the digit0). Let’s try to convert 702 (decimal) to base-26. The usual algorithm is compute 702 % 26 which is 0 so that we would have the last digit as being_. Then we would divide by 26 to obtain 27. We would note that 27 % 26 is 1 so that the penultimate digit isA. Then we would divide by 26 to obtain 1, compute 1 % 26 to obtain 1 and report that the most-significant digit isA. We would returnAA_as the string representing 702 in base-26 with digits (_= 0,A= 1, …Z= 26) (check: 1 * 26^2 + 1 * 26^1 + 0 * 26 = 702). For our purposes, this is wrong. We wanted to get back the stringZZ(because we have 26 digitsA,B,C, …Zrepresenting 1, 2, … 26 (remember, no digit representing the value 0!) so thatZZ= 26 * 26^1 + 26 * 26^0 = 702). It turns out in our system that numbers congruent to 0 modulo 26 should have least-significant digitZ. So this suggests that our algorithm should be check and see ifvalueis congruent to 0 modulo 26. If it is, prepend aZand then prepend the string representing the valuevalue / 26 - 1. This is the algorithm that you see above.