hiimray-co-uk-www-posts/2021/02/SpreadsheetCoord.cs

200 lines
4.7 KiB
C#

using System;
namespace WindowsFormsApp1
{
public class SpreadsheetCoord
{
public static string ConvertToColumnCode(int columnNo, int rowNo)
{
if ((columnNo <= 0) || (rowNo <= 0)) return null;
string rs = string.Empty;
int x = 790;
while (x > 0)
{
int n = (x % 26);
rs = Convert.ToChar(65 + n - 1) + rs;
x -= n;
x = (x / 26);
}
return string.Concat(rs, rowNo.ToString());
}
public static Tuple<int, int> ConvertToCoord(string value)
{
bool checkAlpha = true;
string alpha = string.Empty;
string digit = string.Empty;
for (int i = 0; i < value.Length; i++)
{
if (checkAlpha)
{
if (isAlpha(value[i]))
{
alpha += value[i];
}
else if (isDigit(value[i]))
{
digit += value[i];
checkAlpha = false;
}
else
{
return null;
}
}
else
{
if (isAlpha(value[i]))
{
return null;
}
else if (isDigit(value[i]))
{
digit += value[i];
}
else
{
return null;
}
}
}
// no alpha or digits
if ((alpha.Length <= 0) || (digit.Length <= 0))
{
return null;
}
int rowNo;
if (!int.TryParse(digit, out rowNo))
{
return null;
}
if (rowNo <= 0)
{
return null;
}
int columnNo = convertColumn(alpha);
return new Tuple<int, int>(columnNo, rowNo);
}
public static bool IsValid(string value)
{
bool checkAlpha = true;
string alpha = string.Empty;
string digit = string.Empty;
for (int i = 0; i < value.Length; i++)
{
if (checkAlpha)
{
if (isAlpha(value[i]))
{
alpha += value[i];
}
else if (isDigit(value[i]))
{
digit += value[i];
checkAlpha = false;
}
else
{
return false;
}
}
else
{
if (isAlpha(value[i]))
{
return false;
}
else if (isDigit(value[i]))
{
digit += value[i];
}
else
{
return false;
}
}
}
// no alpha or digits
if ((alpha.Length <= 0) || (digit.Length <= 0))
{
return false;
}
int n;
if (!int.TryParse(digit, out n))
{
return false;
}
if (n <= 0)
{
return false;
}
return true;
}
protected static int convertColumn(string value)
{
int rv = 0;
int len = value.Length - 1;
for (int i = len; i >= 0; i--)
{
int n = (len - i);
int x = convertColumn(value[i]);
rv += (int)(x * Math.Pow(26, n));
}
return rv;
}
protected static int convertColumn(char value)
{
if (isAlpha(value))
{
int code = Convert.ToInt16(char.ToUpper(value));
return (code - 65) + 1;
}
else
{
return 0;
}
}
protected static bool isAlpha(char value)
{
int code = Convert.ToInt16(char.ToUpper(value));
return ((code >= 65) && (code <= 90));
}
protected static bool isDigit(char value)
{
int code = Convert.ToInt16(char.ToUpper(value));
return ((code >= 48) && (code <= 57));
}
}
}