I am trying to get the last cell address from the excel sheet for merging purposes based on starting address and range using the below code.
I have starting cell address like X
and would like to get the end cell address using the given range. For example, starting address is X
, and the range is 7, then the end cell address would be AD
.
I have tried with the below approach and I am getting wrong end cell address
private static readonly char[] BaseChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
private static readonly Dictionary<char, int> CharValues = BaseChars
.Select((c, i) => new { Char = c, Index = i })
.ToDictionary(c => c.Char, c => c.Index);
public static string IntToBase(int value)
{
int targetBase = BaseChars.Length;
// Determine exact number of characters to use.
char[] buffer = new char[Math.Max(
(int)Math.Ceiling(Math.Log(value + 1, targetBase)), 1)];
var i = buffer.Length;
do
{
buffer[--i] = BaseChars[value % targetBase];
value /= targetBase;
}
while (value > 0);
return new string(buffer, i, buffer.Length - i);
}
public static int BaseToInt(string number)
{
_ = number ?? throw new ArgumentNullException(nameof(number));
char[] chrs = number.ToCharArray();
int m = chrs.Length - 1;
int n = BaseChars.Length, x;
int result = 0;
foreach (char c in chrs)
{
x = CharValues[c];
result += x * (int)Math.Pow(n, m--);
}
return result;
}
public static string GetLastCellAddress(string number, int cellCount)
{
int startVal = BaseToInt(number);
return Enumerable.Range(startVal, cellCount).Select(i => IntToBase(i)).Last();
}
And I am using above function like as below
var environmentsLastCellAddress = ExcelBuilderExtensions.GetLastCellAddress(startColumnAddress, spaceTypeLibraryByPropertiesCount);
The above function gives the wrong end address if I have given starting cell address like X
and count is 7
, and I should get the end cell address as AD
instead of I am getting address as BD.
Could anyone please let me know is there anything wrong with the above code? That would be very grateful to me. Many thanks in advance!!