DD.WellWorkover.Cloud/AsbCloudInfrastructure/Services/DailyReport/CellAddress.cs

93 lines
2.7 KiB
C#
Raw Normal View History

using System;
namespace AsbCloudInfrastructure.Services.DailyReport
{
internal class CellAddress
{
const int excelLettersCount = 'Z' - 'A';
public int Row { get; set; }
public int Colunm { get; set; }
public CellAddress(int row, int colunm)
{
Row = row;
Colunm = colunm;
}
public static CellAddress operator + (CellAddress a, CellAddress b)
=> new CellAddress(a.Row + b.Row, a.Colunm + b.Colunm);
public static CellAddress operator - (CellAddress a, CellAddress b)
=> new CellAddress(a.Row - b.Row, a.Colunm - b.Colunm);
public static bool operator == (CellAddress a, CellAddress b)
=> a.Row == b.Row && a.Colunm == b.Colunm;
public static bool operator !=(CellAddress a, CellAddress b)
=> !(a == b);
public static bool TryParse(string cellAddress, out CellAddress parsedAddress)
{
if (cellAddress.Length < 2)
{
parsedAddress = default;
return false;
}
int row = 0;
int col = 0;
for (int i = 0; i < cellAddress.Length; i++)
switch (cellAddress[i])
{
case >= '0' and <= '9':
row = row * 10 + cellAddress[i] - '0';
break;
case >= 'A' and <= 'Z':
col = col * excelLettersCount + cellAddress[i] - 'A';
break;
case >= 'a' and <= 'z':
col = col * excelLettersCount + cellAddress[i] - 'a';
break;
default:
parsedAddress = default;
return false;
}
parsedAddress = new CellAddress(row, col);
return true;
}
public string ToStringA1()
{
string letter = "";
while (Colunm > 0)
{
int modulo = (Colunm - 1) % excelLettersCount;
letter = Convert.ToChar('A' + modulo) + letter;
Colunm = (Colunm - modulo) / excelLettersCount;
}
return letter + Row;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj is null)
{
return false;
}
if (obj is CellAddress address)
return this == address;
return false;
}
public override int GetHashCode()
=> base.GetHashCode();
}
}