Files
spark/src/client/spark_excel/algogen/CellRef.cs
T
2019-07-09 14:39:11 -04:00

250 lines
8.3 KiB
C#

using System;
using System.Diagnostics;
using System.Text;
namespace bts.excel
{
/// <summary>
/// Defines a reference to some Cell instance, whether it exists or not.
/// </summary>
/// <remarks>
/// Static methods are provided for conversion of column names etc.
/// </remarks>
public sealed class CellRef : IComparable, IComparable<CellRef>
{
/// <summary>
/// Constructor for the class: CellRef
/// </summary>
/// <param name="sheetName">Name of the sheet where the cell belongs.</param>
/// <param name="coordinate">Coordinate (column, row) for the cell in the sheet.</param>
public CellRef(string sheetName, (int col1, int row1) coordinate)
{
SheetName = sheetName;
Coordinate = coordinate;
LocalAddress = ConvertCoordToAddress(coordinate);
}
/// <summary>
/// Maximum number of rows, to e compatible with Excel.
/// </summary>
private const int MaxRows = 1048576;
/// <summary>
/// Maximum number of columns, to be compatible with Excel.
/// </summary>
private const int MaxColumns = 16384;
// NOTE: Worksheet and workbook specifications and limits
// http://office.microsoft.com/en-gb/excel-help/excel-specifications-and-limits-HP010342495.aspx
//
// Worksheet size: 1,048,576 rows by 16,384 columns.
// * 1048575 is the highest number representable in 20 bits.
// * 16383 is the highest number representable in 14 bits. That leaves 2 spare bits in a 16-bit word.
// Column width: 255 characters (I'm not sure what the real significance of this is).
// Total number of characters that a cell can contain: 32,767 characters
// * 32766 is the highest number representable in 15 bits. That leaves 1 spare bit in a 16-bit word.
//
/// <summary>
/// Name of the sheet where the cell belongs.
/// </summary>
/// <remarks>
/// All cells belong to some Sheet instance, so this name must never be null or empty.
/// </remarks>
public string SheetName { get; }
/// <summary>
/// Coordinate (column, row) for the cell in the sheet.
/// </summary>
public (int col1, int row1) Coordinate { get; }
public CellRef Offset(int columnOffset, int rowOffset)
{
return new CellRef(SheetName, (Column + columnOffset, Row + rowOffset));
}
public int Column => Coordinate.col1;
public int Row => Coordinate.row1;
public string LocalAddress { get; internal set; }
#region Address conversion
/// <summary>
/// Converts a column identifier, using letters, to a column number.
/// </summary>
/// <param name="columnName">Column identifier using letters.</param>
/// <returns>Column number.</returns>
/// <exception cref="ArgumentOutOfRangeException">When column number exceeds maximum.</exception>
public static int ConvertToColumnNumber(string columnName)
{
var number = 0;
var pow = 1;
for (var i = columnName.Length - 1; i >= 0; i--)
{
number += (columnName[i] - 'A' + 1) * pow;
pow *= 26;
}
if (number > MaxColumns)
{
throw new ArgumentOutOfRangeException(nameof(columnName),
"Column number from columnName exceeds maximum");
}
return number;
}
/// <summary>
/// Converts a column number to a column identifier using letters.
/// </summary>
/// <param name="columnNumber">Column number.</param>
/// <returns>Column identifier using letters.</returns>
/// <exception cref="ArgumentOutOfRangeException">When column number is invalid.</exception>
public static string ConvertToColumnName(int columnNumber)
{
if (columnNumber < 1 || columnNumber > MaxColumns)
{
throw new ArgumentOutOfRangeException(nameof(columnNumber),
"Invalid column number");
}
var dividend = columnNumber;
var columnName = string.Empty;
while (dividend > 0)
{
var modulo = (dividend - 1) % 26;
columnName = Convert.ToChar(65 + modulo) + columnName;
dividend = (dividend - modulo) / 26;
}
return columnName;
}
/// <summary>
/// Converts an address, like "A1", to a cell coordinate.
/// </summary>
/// <param name="address">Cell address, like "A1".</param>
/// <returns>Coordinate of cell on sheet.</returns>
/// <exception cref="ArgumentNullException">When address argument is null.</exception>
/// <exception cref="ArgumentException">When address is invalid.</exception>
public static (int col1, int row1) ConvertAddressToCoord(string address)
{
if (address == null)
{
throw new ArgumentNullException(nameof(address));
}
address = address.Replace("$", string.Empty);
address = address.ToUpper();
var letters = new StringBuilder();
foreach (var c in address)
{
if (c < 'A' || c > 'Z')
{
break;
}
letters.Append(c);
}
if (letters.Length == 0 || letters.Length > 3)
{
throw new ArgumentException(
"Column name requires 1 to 3 letters",
nameof(address));
}
var numbers = address.Substring(letters.Length);
if (numbers.Length == 0)
{
throw new ArgumentException("Row number is required", nameof(address));
}
Debug.Assert(letters.Length + numbers.Length == address.Length);
var row1 = int.Parse(numbers);
var col1 = ConvertToColumnNumber(letters.ToString());
return (col1, row1);
}
/// <summary>
/// Convert cell coordinate to cell address, like "A1".
/// </summary>
/// <param name="coordinate">Coordinate of cell on sheet.</param>
/// <param name="absolute">Provide absolute address, like "$A$1".</param>
/// <returns>Cell address, like "A1", or optionally like "$A$1".</returns>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public static string ConvertCoordToAddress((int col1, int row1) coordinate, bool absolute = false)
{
if (coordinate.row1 < 1 || coordinate.row1 > MaxRows ||
coordinate.col1 < 1 || coordinate.col1 > MaxColumns)
{
throw new ArgumentOutOfRangeException(nameof(coordinate),
"Invalid coordinate");
}
var (col1, row1) = coordinate;
return absolute
? $"${ConvertToColumnName(col1)}${row1}"
: $"{ConvertToColumnName(col1)}{row1}";
}
#endregion
#region IComparable
public int CompareTo(CellRef other)
{
if (other == null) return -1;
return string.Compare(ToString(), other.ToString(),
StringComparison.Ordinal);
}
public int CompareTo(object obj)
{
if (obj.GetType() != GetType()) return -1;
return CompareTo((CellRef)obj);
}
#endregion
#region HashCode & Equals
/// <returns>Unique key</returns>
public override string ToString()
{
if(!string.IsNullOrEmpty(SheetName))
return $"'{SheetName}'!{LocalAddress}";
else
return $"{LocalAddress}";
}
public string to_name()
{
if (!string.IsNullOrEmpty(SheetName))
return $"{SheetName}_{LocalAddress}".ToLowerInvariant();
else
return $"{LocalAddress}".ToLowerInvariant();
}
public override int GetHashCode()
{
return ToString().GetHashCode();
}
public override bool Equals(object obj)
{
if (obj == null) return false;
if (obj != null && !(obj is CellRef))
throw new ArgumentException("Object must be of type CellRef.");
return GetHashCode().Equals(obj.GetHashCode());
}
#endregion
}
}