excel
This commit is contained in:
1 parent
6cf395199e
commit
706e5bc73b
7 files changed
+284
-69
No files matched your search
@@ -0,0 +1,239 @@
|
||||
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()
|
||||
{
|
||||
return $"'{SheetName}'!{LocalAddress}";
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
using LibWorkbooks.LibDep;
|
||||
using LibWorkbooks.Parser;
|
||||
|
||||
namespace spark.excel
|
||||
{
|
||||
internal class Expression : IExpression
|
||||
{
|
||||
private readonly FormulaParser.ExprContext _context;
|
||||
private readonly EvaluationVisitor _visitor;
|
||||
|
||||
public Expression(FormulaParser.ExprContext context, EvaluationVisitor visitor)
|
||||
{
|
||||
_context = context;
|
||||
_visitor = visitor;
|
||||
}
|
||||
|
||||
public object Evaluate()
|
||||
{
|
||||
return _context.Accept(_visitor);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -36,16 +36,16 @@ namespace bts.excel
|
||||
//https://stackoverflow.com/questions/31511610/antlr-source-to-target-language-conversion
|
||||
public class Generate
|
||||
{
|
||||
static ConcurrentDictionary<string, object> _cache = new ConcurrentDictionary<string, object>();
|
||||
|
||||
[ExcelFunction(IsMacroType = true)]
|
||||
static public string bts_generate_code_from_sink(string name, [ExcelArgument(AllowReference=true)] object sink)
|
||||
{
|
||||
ExcelReference rref = (ExcelReference)sink;
|
||||
var form = XlCall.Excel(XlCall.xlfGetCell, 41, rref);
|
||||
var formula = XlCall.Excel(XlCall.xlfGetCell, 41, rref);
|
||||
|
||||
string sheetname = (string)XlCall.Excel(XlCall.xlSheetNm, rref);
|
||||
//var formabs = XlCall.Excel(XlCall.xlfFormulaConvert, form, ExcelDna.
|
||||
|
||||
var antlrstream = new AntlrInputStream(form.ToString());
|
||||
var antlrstream = new AntlrInputStream(formula.ToString());
|
||||
var lexer = new ExcelFormulaLexer(antlrstream);
|
||||
var tokens = new CommonTokenStream(lexer);
|
||||
var parser = new ExcelFormulaParser(tokens);
|
||||
@@ -59,7 +59,7 @@ namespace bts.excel
|
||||
throw new ExcelFormulaException(error_listener.ErrorLocation, error_listener.ErrorMessage);
|
||||
|
||||
//AbstractParseTreeVisitor
|
||||
ExcelFormulaBaseVisitor visitor = new ExcelFormulaBaseVisitor();
|
||||
GeneratorVisitor visitor = new GeneratorVisitor(rref, sheetname);
|
||||
visitor.VisitMain(parsetree);
|
||||
|
||||
return parsetree.ToString();
|
||||
|
||||
@@ -4,28 +4,29 @@ using System.Collections.ObjectModel;
|
||||
using System.Diagnostics;
|
||||
using spark_excel.grammar;
|
||||
|
||||
using ExcelDna.Integration;
|
||||
using Excel = Microsoft.Office.Interop.Excel;
|
||||
|
||||
namespace bts.excel
|
||||
{
|
||||
internal class GeneratorVisitor : ExcelFormulaBaseVisitor<object>
|
||||
{
|
||||
public GeneratorVisitor()
|
||||
{
|
||||
ExcelReference _ref;
|
||||
string _sheetname;
|
||||
public GeneratorVisitor(ExcelReference rref, string sheetname)
|
||||
{
|
||||
_ref = rref;
|
||||
_sheetname = sheetname;
|
||||
}
|
||||
|
||||
private static readonly object FunctionEvaluationLock = new object();
|
||||
|
||||
private FunctionLibrary FunctionLibrary => Workbook.FunctionLibrary;
|
||||
|
||||
private ReadOnlyDictionary<string, Function> Functions => FunctionLibrary.Functions;
|
||||
|
||||
#region Context visitors overrides
|
||||
|
||||
public override object VisitMain(FormulaParser.MainContext context)
|
||||
public override object VisitMain(ExcelFormulaParser.MainContext context)
|
||||
{
|
||||
return context.expr().Accept(this);
|
||||
}
|
||||
|
||||
public override object VisitCellList(FormulaParser.CellListContext context)
|
||||
public override object VisitCellList(ExcelFormulaParser.CellListContext context)
|
||||
{
|
||||
var result = new List<CellRef>();
|
||||
|
||||
@@ -53,7 +54,7 @@ namespace bts.excel
|
||||
return result;
|
||||
}
|
||||
|
||||
public override object VisitMulDiv(FormulaParser.MulDivContext context)
|
||||
public override object VisitMulDiv(ExcelFormulaParser.MulDivContext context)
|
||||
{
|
||||
var expr = context.expr();
|
||||
|
||||
@@ -97,7 +98,7 @@ namespace bts.excel
|
||||
: n1 / n2;
|
||||
}
|
||||
|
||||
public override object VisitAddSub(FormulaParser.AddSubContext context)
|
||||
public override object VisitAddSub(ExcelFormulaParser.AddSubContext context)
|
||||
{
|
||||
var expr = context.expr();
|
||||
|
||||
@@ -152,7 +153,7 @@ namespace bts.excel
|
||||
: n1 - n2;
|
||||
}
|
||||
|
||||
public override object VisitPercentage(FormulaParser.PercentageContext context)
|
||||
public override object VisitPercentage(ExcelFormulaParser.PercentageContext context)
|
||||
{
|
||||
var expr = context.expr();
|
||||
|
||||
@@ -166,7 +167,7 @@ namespace bts.excel
|
||||
return n1 / 100;
|
||||
}
|
||||
|
||||
public override object VisitRelational(FormulaParser.RelationalContext context)
|
||||
public override object VisitRelational(ExcelFormulaParser.RelationalContext context)
|
||||
{
|
||||
var expr = context.expr();
|
||||
|
||||
@@ -200,23 +201,23 @@ namespace bts.excel
|
||||
}
|
||||
}
|
||||
|
||||
public override object VisitError(FormulaParser.ErrorContext context)
|
||||
public override object VisitError(ExcelFormulaParser.ErrorContext context)
|
||||
{
|
||||
return new ErrorValue(context.GetText());
|
||||
}
|
||||
|
||||
public override object VisitString(FormulaParser.StringContext context)
|
||||
public override object VisitString(ExcelFormulaParser.StringContext context)
|
||||
{
|
||||
var str = context.GetText();
|
||||
return str.Substring(1, str.Length - 2);
|
||||
}
|
||||
|
||||
public override object VisitRange(FormulaParser.RangeContext context)
|
||||
public override object VisitRange(ExcelFormulaParser.RangeContext context)
|
||||
{
|
||||
return context.rng().Accept(this);
|
||||
}
|
||||
|
||||
public override object VisitUnary(FormulaParser.UnaryContext context)
|
||||
public override object VisitUnary(ExcelFormulaParser.UnaryContext context)
|
||||
{
|
||||
var expr = context.expr();
|
||||
|
||||
@@ -231,7 +232,7 @@ namespace bts.excel
|
||||
return context.sign.Text == "-" ? -n1 : n1;
|
||||
}
|
||||
|
||||
public override object VisitName(FormulaParser.NameContext context)
|
||||
public override object VisitName(ExcelFormulaParser.NameContext context)
|
||||
{
|
||||
var name = context.GetText();
|
||||
|
||||
@@ -248,7 +249,7 @@ namespace bts.excel
|
||||
return ErrorValue.Name;
|
||||
}
|
||||
|
||||
public override object VisitFunction(FormulaParser.FunctionContext context)
|
||||
public override object VisitFunction(ExcelFormulaParser.FunctionContext context)
|
||||
{
|
||||
var name = context.name.Text;
|
||||
|
||||
@@ -296,17 +297,17 @@ namespace bts.excel
|
||||
return args.HasResult ? args.Result : null;
|
||||
}
|
||||
|
||||
public override object VisitParenthesis(FormulaParser.ParenthesisContext context)
|
||||
public override object VisitParenthesis(ExcelFormulaParser.ParenthesisContext context)
|
||||
{
|
||||
return context.expr().Accept(this);
|
||||
}
|
||||
|
||||
public override object VisitNumber(FormulaParser.NumberContext context)
|
||||
public override object VisitNumber(ExcelFormulaParser.NumberContext context)
|
||||
{
|
||||
return Convert.ToDouble(context.GetText());
|
||||
}
|
||||
|
||||
public override object VisitConcatenate(FormulaParser.ConcatenateContext context)
|
||||
public override object VisitConcatenate(ExcelFormulaParser.ConcatenateContext context)
|
||||
{
|
||||
var expr = context.expr();
|
||||
|
||||
@@ -325,7 +326,7 @@ namespace bts.excel
|
||||
return $"{arg1}{arg2}";
|
||||
}
|
||||
|
||||
public override object VisitPow(FormulaParser.PowContext context)
|
||||
public override object VisitPow(ExcelFormulaParser.PowContext context)
|
||||
{
|
||||
var expr = context.expr();
|
||||
|
||||
@@ -364,7 +365,7 @@ namespace bts.excel
|
||||
return Math.Pow(n1, n2);
|
||||
}
|
||||
|
||||
public override object VisitRangeList(FormulaParser.RangeListContext context)
|
||||
public override object VisitRangeList(ExcelFormulaParser.RangeListContext context)
|
||||
{
|
||||
var result = new List<RangeRef>();
|
||||
|
||||
@@ -391,7 +392,7 @@ namespace bts.excel
|
||||
return result;
|
||||
}
|
||||
|
||||
public override object VisitEquality(FormulaParser.EqualityContext context)
|
||||
public override object VisitEquality(ExcelFormulaParser.EqualityContext context)
|
||||
{
|
||||
var expr = context.expr();
|
||||
|
||||
@@ -436,17 +437,17 @@ namespace bts.excel
|
||||
return EvaluateEquality(context.op.Text, n1, n2);
|
||||
}
|
||||
|
||||
public override object VisitBoolean(FormulaParser.BooleanContext context)
|
||||
public override object VisitBoolean(ExcelFormulaParser.BooleanContext context)
|
||||
{
|
||||
return Convert.ToBoolean(context.GetText().ToLower());
|
||||
}
|
||||
|
||||
public override object VisitCell(FormulaParser.CellContext context)
|
||||
public override object VisitCell(ExcelFormulaParser.CellContext context)
|
||||
{
|
||||
return context.@ref().Accept(this);
|
||||
}
|
||||
|
||||
public override object VisitCellRef(FormulaParser.CellRefContext context)
|
||||
public override object VisitCellRef(ExcelFormulaParser.CellRefContext context)
|
||||
{
|
||||
// Column and row number for the cell.
|
||||
var colRow = context.colRow.Text;
|
||||
@@ -489,7 +490,7 @@ namespace bts.excel
|
||||
return new CellRef(sheet.Name, (col1, row1));
|
||||
}
|
||||
|
||||
public override object VisitRangeRef(FormulaParser.RangeRefContext context)
|
||||
public override object VisitRangeRef(ExcelFormulaParser.RangeRefContext context)
|
||||
{
|
||||
var obj = context.@ref().Accept(this);
|
||||
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using LibWorkbooks.LibDep;
|
||||
|
||||
namespace LibWorkbooks.StandardFunctions
|
||||
namespace bts.excel.functions
|
||||
{
|
||||
public class Average
|
||||
{
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
import "C.g4"
|
||||
|
||||
functionSpecifier(globals,functions) ::= <<
|
||||
class Wrapper {
|
||||
<globals; separator="\n">
|
||||
<functions; separator="\n">
|
||||
}
|
||||
>>
|
||||
@@ -66,14 +66,20 @@
|
||||
<None Include="spark_excel-AddIn.dna" />
|
||||
<None Include="packages.config" />
|
||||
<None Include="Properties\ExcelDna.Build.props" />
|
||||
<None Include="$(IntermediateOutputPath)\*.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../spark_api/spark_api.csproj"/>
|
||||
</ItemGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<Antlr4UseCSharpGenerator>true</Antlr4UseCSharpGenerator>
|
||||
<EnableDefaultAntlrItems>false</EnableDefaultAntlrItems>
|
||||
</PropertyGroup>
|
||||
|
||||
<!-- <ItemGroup>
|
||||
<Antlr4 Include="grammar/ExcelToC.stg">
|
||||
<Antlr4 Include="grammar/ExcelFormula.g4">
|
||||
<Generator>MSBuild:Compile</Generator>
|
||||
<CustomToolNamespace>bts.excel.grammar</CustomToolNamespace>
|
||||
<Listener>True</Listener>
|
||||
@@ -85,7 +91,7 @@
|
||||
<Proto3Excel Include="**/*.proto" />
|
||||
<Proto3Excel Include="../../lib/api/services/*.proto" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="spark_excel_example_2018.xlsm"><CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory></None>
|
||||
</ItemGroup>
|
||||
|
||||
Reference in new issue
Block a user