/**
         * Gets the raw bytes for the formula.  This will include the
         * parsed tokens array.  Used when copying spreadsheets
         *
         * @return the raw record data
         * @exception FormulaException
         */
        public override byte[] getFormulaData()
        {
            if (!getSheet().getWorkbookBof().isBiff8())
            {
                throw new FormulaException(FormulaException.BIFF8_SUPPORTED);
            }

            // Get the tokens, taking into account the mapping from shared
            // formula specific values into normal values
            FormulaParser fp = new FormulaParser
                                   (getTokens(), this,
                                   getExternalSheet(), getNameTable(),
                                   getSheet().getWorkbook().getSettings());

            fp.parse();
            byte[] rpnTokens = fp.getBytes();

            byte[] data = new byte[rpnTokens.Length + 22];

            // Set the standard info for this cell
            IntegerHelper.getTwoBytes(getRow(), data, 0);
            IntegerHelper.getTwoBytes(getColumn(), data, 2);
            IntegerHelper.getTwoBytes(getXFIndex(), data, 4);

            // Set the two most significant bytes of the value to be 0xff in
            // order to identify this as a string
            data[6]  = 0;
            data[12] = (byte)0xff;
            data[13] = (byte)0xff;

            // Now copy in the parsed tokens
            System.Array.Copy(rpnTokens, 0, data, 22, rpnTokens.Length);
            IntegerHelper.getTwoBytes(rpnTokens.Length, data, 20);

            // Lop off the standard information
            byte[] d = new byte[data.Length - 6];
            System.Array.Copy(data, 6, d, 0, data.Length - 6);

            return(d);
        }
示例#2
0
        /**
         * Initializes the string and the formula bytes.  In order to get
         * access to the workbook settings, the object is not initialized until
         * it is added to the sheet
         *
         * @param ws the workbook settings
         * @param es the external sheet
         * @param nt the name table
         */
        private void initialize(WorkbookSettings ws, ExternalSheet es,
                                WorkbookMethods nt)
        {
            if (copiedFrom != null)
            {
                initializeCopiedFormula(ws, es, nt);
                return;
            }

            parser = new FormulaParser(formulaToParse, es, nt, ws);

            try
            {
                parser.parse();
                formulaString = parser.getFormula();
                formulaBytes  = parser.getBytes();
            }
            catch (FormulaException e)
            {
                //logger.warn(e.Message + " when parsing formula " + formulaToParse + " in cell " +
                //   getSheet().getName() + "!" +
                //     CellReferenceHelper.getCellReference(getColumn(), getRow()));

                try
                {
                    // try again, with an error formula
                    formulaToParse = "ERROR(1)";
                    parser         = new FormulaParser(formulaToParse, es, nt, ws);
                    parser.parse();
                    formulaString = parser.getFormula();
                    formulaBytes  = parser.getBytes();
                }
                catch (FormulaException e2)
                {
                    // fail silently
                    //logger.error(string.Empty, e2);
                }
            }
        }
示例#3
0
 private static void CalcChain(ExcelWorkbook wb, FormulaParser parser, DependencyChain dc)
 {
     foreach (var ix in dc.CalcOrder)
     {
         var item = dc.list[ix];
         try
         {
             var ws = wb.Worksheets.GetBySheetID(item.SheetID);
             var v  = parser.ParseCell(item.Tokens, ws == null ? "" : ws.Name, item.Row, item.Column);
             SetValue(wb, item, v);
         }
         catch (FormatException fe)
         {
             throw (fe);
         }
         catch (Exception e)
         {
             var error = ExcelErrorValue.Parse(ExcelErrorValue.Values.Value);
             SetValue(wb, item, error);
         }
     }
 }
示例#4
0
        public void RunTest()
        {
            var parserInstance = new FormulaParser();
            var builder        = new ParserBuilder <FormulaToken, IFormula>();
            var parserResult   = builder.BuildParser(parserInstance, ParserType.EBNF_LL_RECURSIVE_DESCENT, "formulae");

            Assert.True(parserResult.IsOk);
            var source = @"

aaa = -1 * (bbb + 1)
bbb = ccc + 2
ccc = 3 + 3 


";
            var t      = parserResult.Result.Parse(source);

            Assert.True(t.IsOk);

            var  form       = t.Result as Formulae;
            var  depBuilder = new Dependencies();
            bool isCyclic   = depBuilder.Build(t.Result as Formulae);

            Assert.False(isCyclic);
            var checker = new TypeChecker();

            checker.Type(form, depBuilder.DependenciesDictionary);

            var formulaeEngine = new FormulaeEngine(depBuilder, form);

            Assert.Equal(6.0, formulaeEngine.GetValue("ccc"));
            Assert.Equal(8.0, formulaeEngine.GetValue("bbb"));
            Assert.Equal(-9.0, formulaeEngine.GetValue("aaa"));
            formulaeEngine.Set("ccc", 10.0);
            Assert.Equal(10.0, formulaeEngine.GetValue("ccc"));
            Assert.Equal(12.0, formulaeEngine.GetValue("bbb"));
            Assert.Equal(-13.0, formulaeEngine.GetValue("aaa"));
        }
示例#5
0
        /**
         * Error formula specific exception handling.  Can't really create
         * a formula (as it will look for a cell of that name, so just
         * create a STRING record containing the contents
         *
         * @return the bodged data
         */
        public override byte[] handleFormulaException()
        {
            byte[] expressiondata = null;
            byte[] celldata       = base.getCellData();

            // Generate an appropriate dummy formula
            WritableWorkbookImpl w      = getSheet().getWorkbook();
            FormulaParser        parser = new FormulaParser(getValue().ToString(), w, w, w.getSettings());

            // Get the bytes for the dummy formula
            try
            {
                parser.parse();
            }
            catch (FormulaException e2)
            {
                //logger.warn(e2.Message);
            }
            byte[] formulaBytes = parser.getBytes();
            expressiondata = new byte[formulaBytes.Length + 16];
            IntegerHelper.getTwoBytes(formulaBytes.Length, expressiondata, 14);
            System.Array.Copy(formulaBytes, 0, expressiondata, 16,
                              formulaBytes.Length);

            // Set the recalculate on load bit
            expressiondata[8] |= 0x02;

            byte[] data = new byte[celldata.Length +
                                   expressiondata.Length];
            System.Array.Copy(celldata, 0, data, 0, celldata.Length);
            System.Array.Copy(expressiondata, 0, data,
                              celldata.Length, expressiondata.Length);

            // Store the value in the formula
            DoubleHelper.getIEEEBytes(getValue(), data, 6);

            return(data);
        }
示例#6
0
        private static void CalcChain(ExcelWorkbook wb, FormulaParser parser, DependencyChain dc, ExcelCalculationOption options)
        {
            wb.FormulaParser.Configure(config =>
            {
                config.AllowCircularReferences      = options.AllowCircularReferences;
                config.PrecisionAndRoundingStrategy = options.PrecisionAndRoundingStrategy;
            });
            var debug = parser.Logger != null;

            foreach (var ix in dc.CalcOrder)
            {
                var item = dc.list[ix];
                try
                {
                    var ws = wb.Worksheets.GetBySheetID(item.SheetID);
                    var v  = parser.ParseCell(item.Tokens, ws == null ? "" : ws.Name, item.Row, item.Column);
                    SetValue(wb, item, v);
                    if (debug)
                    {
                        parser.Logger.LogCellCounted();
                    }
                    Thread.Sleep(0);
                }
                catch (FormatException fe)
                {
                    throw (fe);
                }
                catch (CircularReferenceException cre)
                {
                    throw cre;
                }
                catch (Exception e)
                {
                    var error = ExcelErrorValue.Parse(ExcelErrorValue.Values.Value);
                    SetValue(wb, item, error);
                }
            }
        }
示例#7
0
        public void TestConvertSharedFormulas()
        {
            IWorkbook wb = new HSSFWorkbook();
            HSSFEvaluationWorkbook fpb = HSSFEvaluationWorkbook.Create(wb);

            Ptg[] sharedFormula, ConvertedFormula;

            SharedFormula sf = new SharedFormula(SpreadsheetVersion.EXCEL97);

            sharedFormula    = FormulaParser.Parse("A2", fpb, FormulaType.Cell, -1, -1);
            ConvertedFormula = sf.ConvertSharedFormulas(sharedFormula, 0, 0);
            ConfirmOperandClasses(sharedFormula, ConvertedFormula);
            //conversion relative to [0,0] should return the original formula
            Assert.AreEqual(FormulaRenderer.ToFormulaString(fpb, ConvertedFormula), "A2");

            ConvertedFormula = sf.ConvertSharedFormulas(sharedFormula, 1, 0);
            ConfirmOperandClasses(sharedFormula, ConvertedFormula);
            //one row down
            Assert.AreEqual(FormulaRenderer.ToFormulaString(fpb, ConvertedFormula), "A3");

            ConvertedFormula = sf.ConvertSharedFormulas(sharedFormula, 1, 1);
            ConfirmOperandClasses(sharedFormula, ConvertedFormula);
            //one row down and one cell right
            Assert.AreEqual(FormulaRenderer.ToFormulaString(fpb, ConvertedFormula), "B3");

            sharedFormula    = FormulaParser.Parse("SUM(A1:C1)", fpb, FormulaType.Cell, -1, -1);
            ConvertedFormula = sf.ConvertSharedFormulas(sharedFormula, 0, 0);
            ConfirmOperandClasses(sharedFormula, ConvertedFormula);
            Assert.AreEqual(FormulaRenderer.ToFormulaString(fpb, ConvertedFormula), "SUM(A1:C1)");

            ConvertedFormula = sf.ConvertSharedFormulas(sharedFormula, 1, 0);
            ConfirmOperandClasses(sharedFormula, ConvertedFormula);
            Assert.AreEqual(FormulaRenderer.ToFormulaString(fpb, ConvertedFormula), "SUM(A2:C2)");

            ConvertedFormula = sf.ConvertSharedFormulas(sharedFormula, 1, 1);
            ConfirmOperandClasses(sharedFormula, ConvertedFormula);
            Assert.AreEqual(FormulaRenderer.ToFormulaString(fpb, ConvertedFormula), "SUM(B2:D2)");
        }
示例#8
0
        /**
         * Parse cell formula and re-assemble it back using the specified FormulaRenderingWorkbook.
         *
         * @param cell the cell to update
         * @param frwb the formula rendering workbbok that returns new sheet name
         */
        private void UpdateFormula(XSSFCell cell, String oldName, String newName)
        {
            CT_CellFormula f = cell.GetCTCell().f;

            if (f != null)
            {
                String formula = f.Value;
                if (formula != null && formula.Length > 0)
                {
                    int   sheetIndex = _wb.GetSheetIndex(cell.Sheet);
                    Ptg[] ptgs       = FormulaParser.Parse(formula, _fpwb, FormulaType.Cell, sheetIndex, -1);
                    foreach (Ptg ptg in ptgs)
                    {
                        UpdatePtg(ptg, oldName, newName);
                    }
                    String updatedFormula = FormulaRenderer.ToFormulaString(_fpwb, ptgs);
                    if (!formula.Equals(updatedFormula))
                    {
                        f.Value = (updatedFormula);
                    }
                }
            }
        }
示例#9
0
        public void TestRunCostumVisitor()
        {
            var variables = new Dictionary <string, double>
            {
                ["x"] = 2
            };

            var parser = FormulaParser.Create();

            var node = parser.Parse("1 + 2");

            var transformedNode1 = parser.RunVisitor(node, new SwitchPlusAndMinus());

            var transformedNode2 = parser.RunVisitor("1 + 2", new SwitchPlusAndMinus());

            var transformedNode3 = parser.RunVisitor("1 + x", new SwitchPlusAndMinus(), variables);

            foreach (var transformedNode in new[] { transformedNode1, transformedNode2, transformedNode3 })
            {
                var result = parser.Evaluate(transformedNode, variables);
                Assert.AreEqual(-1.0, result.Value);
            }
        }
        public void TestAddFunction()
        {
            var parser = FormulaParser.CreateBuilder()
                         .ConfigureFunctions(functions =>
            {
                functions.Add("MyFunction0", () => 0);
                functions.Add("MyFunction1", a => a);
                functions.Add("MyFunction2", (a, b) => a + b);
                functions.Add("MyFunction3", (a, b, c) => a + b + c);
                functions.Add("MyFunction4", (a, b, c, d) => a + b + c + d);
                functions.Add("MyFunction5", (a, b, c, d, e) => a + b + c + d + e);
                functions.Add("MyFunctionN", args => args.Aggregate((x, y) => x + y));
            })
                         .Build();

            Assert.AreEqual(0.0, parser.Evaluate("MyFunction0()").Value);
            Assert.AreEqual(1.0, parser.Evaluate("MyFunction1(1)").Value);
            Assert.AreEqual(3.0, parser.Evaluate("MyFunction2(1, 2)").Value);
            Assert.AreEqual(6.0, parser.Evaluate("MyFunction3(1, 2, 3)").Value);
            Assert.AreEqual(10.0, parser.Evaluate("MyFunction4(1, 2, 3, 4)").Value);
            Assert.AreEqual(15.0, parser.Evaluate("MyFunction5(1, 2, 3, 4, 5)").Value);
            Assert.AreEqual(55.0, parser.Evaluate("MyFunctionN(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)").Value);
        }
示例#11
0
        public void TestCase002()
        {
            bool   equal;
            int    retVal   = Constants.Failure;
            string errorMsg = string.Empty;
            double expectedElementComposition;
            string Formula = "C8H8ClNO3S", formulaSummary;
            double expectedMolarMass = 233.68, actualMolarMass;
            Dictionary <string, double> expectedComposition = new Dictionary <string, double>()
            {
                { "C", 41.12 },
                { "H", 3.45 },
                { "Cl", 15.17 },
                { "N", 5.99 },
                { "O", 20.45 },
                { "S", 13.72 },
            };

            FormulaParser parser = new FormulaParser();

            retVal = parser.SetFormula(Formula, out formulaSummary, out actualMolarMass);
            Assert.AreEqual(Constants.Success, retVal);
            equal = Math.Abs(expectedMolarMass - actualMolarMass) <= allowedDifference;
            Assert.IsTrue(equal);

            IDictionary <string, double> actualComposition = parser.ParseElements(out retVal);

            Assert.AreEqual(Constants.Success, retVal);
            Assert.AreEqual(expectedComposition.Count, actualComposition.Count);

            foreach (KeyValuePair <string, double> kvp in actualComposition)
            {
                expectedElementComposition = expectedComposition[kvp.Key];
                equal = Math.Abs(expectedElementComposition - kvp.Value) <= allowedDifference;
                Assert.IsTrue(equal);
            }
        }
示例#12
0
        public void TestConfigureRegistry()
        {
            var parser = FormulaParser
                         .CreateBuilder()
                         .ConfigureFunctions(functions =>
            {
                functions.RemoveAll();
                functions.Add("sum", args => args.Aggregate((x, y) => x + y));
                functions.Add("avg", args => args.Average());
            })
                         .ConfigureConstats(constants =>
            {
                constants.RemoveAll();
                constants.Add("X", 1);
                constants.Add("Y", 2);
                constants.Add("Z", 3);
            })
                         .Build();

            var result = parser.Evaluate("sum(X, Y, Z, 100)");

            Assert.IsTrue(result.Success, string.Join(", ", (string)result.Error));
            Assert.AreEqual(106.0, result.Value);
        }
示例#13
0
        public void TestCase003()
        {
            bool   equal;
            int    retVal   = Constants.Failure;
            string errorMsg = string.Empty;
            double expectedElementComposition;
            string Formula = "C8H7HgNaO3", formulaSummary;
            double expectedMolarMass = 374.74, actualMolarMass;
            Dictionary <string, double> expectedComposition = new Dictionary <string, double>()
            {
                { "C", 25.64 },
                { "H", 1.88 },
                { "Hg", 53.53 },
                { "Na", 6.14 },
                { "O", 12.81 }
            };

            FormulaParser parser = new FormulaParser();

            retVal = parser.SetFormula(Formula, out formulaSummary, out actualMolarMass);
            Assert.AreEqual(Constants.Success, retVal);
            equal = Math.Abs(expectedMolarMass - actualMolarMass) <= allowedDifference;
            Assert.IsTrue(equal);

            IDictionary <string, double> actualComposition = parser.ParseElements(out retVal);

            Assert.AreEqual(Constants.Success, retVal);
            Assert.AreEqual(expectedComposition.Count, actualComposition.Count);

            foreach (KeyValuePair <string, double> kvp in actualComposition)
            {
                expectedElementComposition = expectedComposition[kvp.Key];
                equal = Math.Abs(expectedElementComposition - kvp.Value) <= allowedDifference;
                Assert.IsTrue(equal);
            }
        }
示例#14
0
        /**
         * Shift a formula using the supplied FormulaShifter
         *
         * @param row     the row of the cell this formula belongs to. Used to get a reference to the parent workbook.
         * @param formula the formula to shift
         * @param Shifter the FormulaShifter object that operates on the Parsed formula tokens
         * @return the Shifted formula if the formula was Changed,
         *         <code>null</code> if the formula wasn't modified
         */
        private static String ShiftFormula(XSSFRow row, String formula, FormulaShifter Shifter)
        {
            ISheet    sheet            = row.Sheet;
            IWorkbook wb               = sheet.Workbook;
            int       sheetIndex       = wb.GetSheetIndex(sheet);
            XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.Create(wb);

            try
            {
                Ptg[]  ptgs        = FormulaParser.Parse(formula, fpb, FormulaType.Cell, sheetIndex);
                String ShiftedFmla = null;
                if (Shifter.AdjustFormula(ptgs, sheetIndex))
                {
                    ShiftedFmla = FormulaRenderer.ToFormulaString(fpb, ptgs);
                }
                return(ShiftedFmla);
            }
            catch (FormulaParseException fpe)
            {
                // Log, but don't change, rather than breaking
                Console.WriteLine("Error shifting formula on row {0}, {1}", row.RowNum, fpe);
                return(formula);
            }
        }
示例#15
0
        public void TestCase008()
        {
            bool   equal;
            int    retVal   = Constants.Failure;
            string errorMsg = string.Empty;
            double expectedElementComposition;
            string Formula = "C20H14CaO8S2", formulaSummary;
            double expectedMolarMass = 486.54, actualMolarMass;
            Dictionary <string, double> expectedComposition = new Dictionary <string, double>()
            {
                { "C", 49.37 },
                { "H", 2.90 },
                { "Ca", 8.24 },
                { "S", 13.18 },
                { "O", 26.31 }
            };

            FormulaParser parser = new FormulaParser();

            retVal = parser.SetFormula(Formula, out formulaSummary, out actualMolarMass);
            Assert.AreEqual(Constants.Success, retVal);
            equal = Math.Abs(expectedMolarMass - actualMolarMass) <= allowedDifference;
            Assert.IsTrue(equal);

            IDictionary <string, double> actualComposition = parser.ParseElements(out retVal);

            Assert.AreEqual(Constants.Success, retVal);
            Assert.AreEqual(expectedComposition.Count, actualComposition.Count);

            foreach (KeyValuePair <string, double> kvp in actualComposition)
            {
                expectedElementComposition = expectedComposition[kvp.Key];
                equal = Math.Abs(expectedElementComposition - kvp.Value) <= allowedDifference;
                Assert.IsTrue(equal);
            }
        }
        public void Setup()
        {
            var excelDataProvider = MockRepository.GenerateStub <ExcelDataProvider>();

            _parser = new FormulaParser(excelDataProvider);
        }
示例#17
0
 public static Ptg[] Parse(String formula, HSSFWorkbook book)
 {
     FormulaParser fp = new FormulaParser(formula, book);
     fp.Parse();
     return fp.GetRPNPtg();
 }
示例#18
0
        public void UpdateConditionalFormatting(FormulaShifter Shifter)
        {
            IWorkbook workbook   = this.sheet.Workbook;
            int       sheetIndex = workbook.GetSheetIndex((ISheet)this.sheet);
            XSSFEvaluationWorkbook          evaluationWorkbook     = XSSFEvaluationWorkbook.Create(workbook);
            List <CT_ConditionalFormatting> conditionalFormatting1 = this.sheet.GetCTWorksheet().conditionalFormatting;

            for (int index1 = 0; conditionalFormatting1 != null && index1 < conditionalFormatting1.Count; ++index1)
            {
                CT_ConditionalFormatting conditionalFormatting2 = conditionalFormatting1[index1];
                List <CellRangeAddress>  cellRangeAddressList1  = new List <CellRangeAddress>();
                foreach (object obj in conditionalFormatting2.sqref)
                {
                    string str     = obj.ToString();
                    char[] chArray = new char[1] {
                        ' '
                    };
                    foreach (string reference in str.Split(chArray))
                    {
                        cellRangeAddressList1.Add(CellRangeAddress.ValueOf(reference));
                    }
                }
                bool flag = false;
                List <CellRangeAddress> cellRangeAddressList2 = new List <CellRangeAddress>();
                for (int index2 = 0; index2 < cellRangeAddressList1.Count; ++index2)
                {
                    CellRangeAddress cra = cellRangeAddressList1[index2];
                    CellRangeAddress cellRangeAddress = XSSFRowShifter.ShiftRange(Shifter, cra, sheetIndex);
                    if (cellRangeAddress == null)
                    {
                        flag = true;
                    }
                    else
                    {
                        cellRangeAddressList2.Add(cellRangeAddress);
                        if (cellRangeAddress != cra)
                        {
                            flag = true;
                        }
                    }
                }
                if (flag)
                {
                    if (cellRangeAddressList2.Count == 0)
                    {
                        conditionalFormatting1.RemoveAt(index1);
                        continue;
                    }
                    List <string> stringList = new List <string>();
                    foreach (CellRangeAddress cellRangeAddress in cellRangeAddressList2)
                    {
                        stringList.Add(cellRangeAddress.FormatAsString());
                    }
                    conditionalFormatting2.sqref = stringList;
                }
                foreach (CT_CfRule ctCfRule in conditionalFormatting2.cfRule)
                {
                    List <string> formula = ctCfRule.formula;
                    for (int index2 = 0; index2 < formula.Count; ++index2)
                    {
                        Ptg[] ptgs = FormulaParser.Parse(formula[index2], (IFormulaParsingWorkbook)evaluationWorkbook, FormulaType.CELL, sheetIndex);
                        if (Shifter.AdjustFormula(ptgs, sheetIndex))
                        {
                            string formulaString = FormulaRenderer.ToFormulaString((IFormulaRenderingWorkbook)evaluationWorkbook, ptgs);
                            formula[index2] = formulaString;
                        }
                    }
                }
            }
        }
示例#19
0
        /**
         * @param formulaType a constant from {@link FormulaType}
         * @return the parsed formula tokens
         */

        public static Ptg[] Parse(string formula, HSSFWorkbook workbook, FormulaType formulaType)
        {
            return(FormulaParser.Parse(formula, CreateParsingWorkbook(workbook), formulaType));
        }
示例#20
0
 private static Ptg[] Parse(IFormulaParsingWorkbook fpb, String fmla)
 {
     return(FormulaParser.Parse(fmla, fpb, FormulaType.Cell, -1));
 }
示例#21
0
 public static Ptg[] Parse(String formula, FormulaParsingWorkbook workbook, int formulaType)
 {
     FormulaParser fp = new FormulaParser(formula, workbook);
     fp.Parse();
     return fp.GetRPNPtg(formulaType);
 }
示例#22
0
 /**
  * @param formula     the formula to parse
  * @param workbook    the parent workbook
  * @param formulaType a constant from {@link FormulaType}
  * @param sheetIndex  the 0-based index of the sheet this formula belongs to.
  * The sheet index is required to resolve sheet-level names. <code>-1</code> means that
  * the scope of the name will be ignored and  the parser will match named ranges only by name
  *
  * @return the parsed formula tokens
  */
 public static Ptg[] Parse(String formula, HSSFWorkbook workbook, FormulaType formulaType, int sheetIndex)
 {
     return(FormulaParser.Parse(formula, CreateParsingWorkbook(workbook), formulaType, sheetIndex));
 }
示例#23
0
 private static Ptg[] Parse(XSSFEvaluationWorkbook fpb, String fmla)
 {
     return(FormulaParser.Parse(fmla, fpb, FormulaType.CELL, -1));
 }
示例#24
0
 /**
  * Parse a formula into a array of tokens
  *
  * @param formula	 the formula to parse
  * @param workbook	the parent workbook
  * @param formulaType the type of the formula, see {@link FormulaType}
  * @param sheetIndex  the 0-based index of the sheet this formula belongs to.
  * The sheet index is required to resolve sheet-level names. <code>-1</code> means that
  * the scope of the name will be ignored and  the parser will match names only by name
  *
  * @return array of parsed tokens
  * @throws FormulaParseException if the formula is unparsable
  */
 public static Ptg[] Parse(String formula, IFormulaParsingWorkbook workbook, FormulaType formulaType, int sheetIndex)
 {
     FormulaParser fp = new FormulaParser(formula, workbook, sheetIndex);
     fp.Parse();
     return fp.GetRPNPtg(formulaType);
 }
示例#25
0
        private string ConvertSharedFormula(int si)
        {
            XSSFSheet      sheet         = (XSSFSheet)this.Sheet;
            CT_CellFormula sharedFormula = sheet.GetSharedFormula(si);

            if (sharedFormula == null)
            {
                throw new InvalidOperationException("Master cell of a shared formula with sid=" + (object)si + " was not found");
            }
            string           formula          = sharedFormula.Value;
            CellRangeAddress cellRangeAddress = CellRangeAddress.ValueOf(sharedFormula.@ref);
            int sheetIndex = sheet.Workbook.GetSheetIndex((ISheet)sheet);
            XSSFEvaluationWorkbook evaluationWorkbook = XSSFEvaluationWorkbook.Create(sheet.Workbook);

            Ptg[] ptgs = new SharedFormula(SpreadsheetVersion.EXCEL2007).ConvertSharedFormulas(FormulaParser.Parse(formula, (IFormulaParsingWorkbook)evaluationWorkbook, FormulaType.CELL, sheetIndex), this.RowIndex - cellRangeAddress.FirstRow, this.ColumnIndex - cellRangeAddress.FirstColumn);
            return(FormulaRenderer.ToFormulaString((IFormulaRenderingWorkbook)evaluationWorkbook, ptgs));
        }
示例#26
0
        /**
         * Constructor
         */
        public DVParser(byte[] data,
                        ExternalSheet es,
                        WorkbookMethods nt,
                        WorkbookSettings ws)
        {
            Assert.verify(nt != null);

            wasCopied = false;
            int options = IntegerHelper.getInt(data[0], data[1], data[2], data[3]);

            int typeVal = options & 0xf;

            type = DVType.getType(typeVal);

            int errorStyleVal = (options & 0x70) >> 4;

            errorStyle = ErrorStyle.getErrorStyle(errorStyleVal);

            int conditionVal = (options & 0xf00000) >> 20;

            condition = Condition.getCondition(conditionVal);

            stringListGiven   = (options & STRING_LIST_GIVEN_MASK) != 0;
            emptyCellsAllowed = (options & EMPTY_CELLS_ALLOWED_MASK) != 0;
            suppressArrow     = (options & SUPPRESS_ARROW_MASK) != 0;
            showPrompt        = (options & SHOW_PROMPT_MASK) != 0;
            showError         = (options & SHOW_ERROR_MASK) != 0;

            int pos    = 4;
            int length = IntegerHelper.getInt(data[pos], data[pos + 1]);

            if (length > 0 && data[pos + 2] == 0)
            {
                promptTitle = StringHelper.getString(data, length, pos + 3, ws);
                pos        += length + 3;
            }
            else if (length > 0)
            {
                promptTitle = StringHelper.getUnicodeString(data, length, pos + 3);
                pos        += length * 2 + 3;
            }
            else
            {
                pos += 3;
            }

            length = IntegerHelper.getInt(data[pos], data[pos + 1]);
            if (length > 0 && data[pos + 2] == 0)
            {
                errorTitle = StringHelper.getString(data, length, pos + 3, ws);
                pos       += length + 3;
            }
            else if (length > 0)
            {
                errorTitle = StringHelper.getUnicodeString(data, length, pos + 3);
                pos       += length * 2 + 3;
            }
            else
            {
                pos += 3;
            }

            length = IntegerHelper.getInt(data[pos], data[pos + 1]);
            if (length > 0 && data[pos + 2] == 0)
            {
                promptText = StringHelper.getString(data, length, pos + 3, ws);
                pos       += length + 3;
            }
            else if (length > 0)
            {
                promptText = StringHelper.getUnicodeString(data, length, pos + 3);
                pos       += length * 2 + 3;
            }
            else
            {
                pos += 3;
            }

            length = IntegerHelper.getInt(data[pos], data[pos + 1]);
            if (length > 0 && data[pos + 2] == 0)
            {
                errorText = StringHelper.getString(data, length, pos + 3, ws);
                pos      += length + 3;
            }
            else if (length > 0)
            {
                errorText = StringHelper.getUnicodeString(data, length, pos + 3);
                pos      += length * 2 + 3;
            }
            else
            {
                pos += 3;
            }

            int formula1Length = IntegerHelper.getInt(data[pos], data[pos + 1]);

            pos += 4;
            int formula1Pos = pos;

            pos += formula1Length;

            int formula2Length = IntegerHelper.getInt(data[pos], data[pos + 1]);

            pos += 4;
            int formula2Pos = pos;

            pos += formula2Length;

            pos += 2;

            row1 = IntegerHelper.getInt(data[pos], data[pos + 1]);
            pos += 2;

            row2 = IntegerHelper.getInt(data[pos], data[pos + 1]);
            pos += 2;

            column1 = IntegerHelper.getInt(data[pos], data[pos + 1]);
            pos    += 2;

            column2 = IntegerHelper.getInt(data[pos], data[pos + 1]);
            pos    += 2;

            hasExtendedCellsValidation = (row1 == row2 && column1 == column2) ? false : true;

            // Do the formulas
            try
            {
                // First, create a temporary  blank cell for any formula relative
                // references
                EmptyCell tmprt = new EmptyCell(column1, row1);

                if (formula1Length != 0)
                {
                    byte[] tokens = new byte[formula1Length];
                    System.Array.Copy(data, formula1Pos, tokens, 0, formula1Length);
                    formula1 = new FormulaParser(tokens, tmprt, es, nt, ws,
                                                 ParseContext.DATA_VALIDATION);
                    formula1.parse();
                }

                if (formula2Length != 0)
                {
                    byte[] tokens = new byte[formula2Length];
                    System.Array.Copy(data, formula2Pos, tokens, 0, formula2Length);
                    formula2 = new FormulaParser(tokens, tmprt, es, nt, ws,
                                                 ParseContext.DATA_VALIDATION);
                    formula2.parse();
                }
            }
            catch (FormulaException e)
            {
                //logger.warn(e.Message + " for cells " +
                //    CellReferenceHelper.getCellReference(column1,row1) + "-" +
                //    CellReferenceHelper.getCellReference(column2,row2));
            }
        }
示例#27
0
        public void UpdateConditionalFormatting(FormulaShifter Shifter)
        {
            IWorkbook wb         = sheet.Workbook;
            int       sheetIndex = wb.GetSheetIndex(sheet);


            XSSFEvaluationWorkbook          fpb         = XSSFEvaluationWorkbook.Create(wb);
            CT_Worksheet                    ctWorksheet = sheet.GetCTWorksheet();
            List <CT_ConditionalFormatting> conditionalFormattingArray = ctWorksheet.conditionalFormatting;

            // iterate backwards due to possible calls to ctWorksheet.removeConditionalFormatting(j)
            for (int j = conditionalFormattingArray.Count - 1; j >= 0; j--)
            {
                CT_ConditionalFormatting cf = conditionalFormattingArray[j];

                List <CellRangeAddress> cellRanges = new List <CellRangeAddress>();
                String[] regions = cf.sqref.ToString().Split(new char[] { ' ' });
                for (int i = 0; i < regions.Length; i++)
                {
                    cellRanges.Add(CellRangeAddress.ValueOf(regions[i]));
                }

                bool Changed = false;
                List <CellRangeAddress> temp = new List <CellRangeAddress>();
                for (int i = 0; i < cellRanges.Count; i++)
                {
                    CellRangeAddress craOld = cellRanges[i];
                    CellRangeAddress craNew = ShiftRange(Shifter, craOld, sheetIndex);
                    if (craNew == null)
                    {
                        Changed = true;
                        continue;
                    }
                    temp.Add(craNew);
                    if (craNew != craOld)
                    {
                        Changed = true;
                    }
                }

                if (Changed)
                {
                    int nRanges = temp.Count;
                    if (nRanges == 0)
                    {
                        conditionalFormattingArray.RemoveAt(j);
                        continue;
                    }
                    string refs = string.Empty;
                    foreach (CellRangeAddress a in temp)
                    {
                        if (refs.Length == 0)
                        {
                            refs = a.FormatAsString();
                        }
                        else
                        {
                            refs += " " + a.FormatAsString();
                        }
                    }
                    cf.sqref = refs;
                }

                foreach (CT_CfRule cfRule in cf.cfRule)
                {
                    List <String> formulas = cfRule.formula;
                    for (int i = 0; i < formulas.Count; i++)
                    {
                        String formula = formulas[i];
                        Ptg[]  ptgs    = FormulaParser.Parse(formula, fpb, FormulaType.Cell, sheetIndex);
                        if (Shifter.AdjustFormula(ptgs, sheetIndex))
                        {
                            String ShiftedFmla = FormulaRenderer.ToFormulaString(fpb, ptgs);
                            formulas[i] = ShiftedFmla;
                        }
                    }
                }
            }
        }
        public void Setup()
        {
            var excelDataProvider = A.Fake <ExcelDataProvider>();

            _parser = new FormulaParser(excelDataProvider);
        }
示例#29
0
 /**
  * Convenience method for parsing cell formulas. see {@link #parse(String, HSSFWorkbook, int)}
  */
 public static Ptg[] Parse(String formula, HSSFWorkbook workbook)
 {
     return(FormulaParser.Parse(formula, CreateParsingWorkbook(workbook)));
 }
        protected override void DoQuickLoad(BinaryReader BR, FormulaParser ActiveParser)
        {
            base.DoQuickLoad(BR, ActiveParser);

            LastEvaluationResult = BR.ReadString();
        }
示例#31
0
        public Ptg[] getFormulaTokens(SXSSFEvaluationCell evalCell)
        {
            SXSSFCell cell = ((SXSSFEvaluationCell)evalCell).getSXSSFCell();

            return(FormulaParser.Parse(cell.CellFormula, this, FormulaType.Cell, _uBook.GetSheetIndex(cell.Sheet)));
        }
示例#32
0
 public AttackAnimations GetAttackAnimations(FormulaParser ActiveParser)
 {
     return(Animations[0].Animations);
 }
示例#33
0
文件: User.cs 项目: DomGrieco/server
        public override void Attack(Direction direction, Castable castObject = null, Creature target = null)
        {
            if (target != null)
            {
                var damage = castObject.Effects.Damage;

                if (damage.Formula == null) //will need to be expanded. also will need to account for damage scripts
                {
                    var simple = damage.Simple;
                    var damageType = EnumUtil.ParseEnum<Enums.DamageType>(damage.Type.ToString(), Enums.DamageType.Magical);
                    Random rand = new Random();
                    var dmg = rand.Next(Convert.ToInt32(simple.Min), Convert.ToInt32(simple.Max)); //these need to be set to integers as attributes. note to fix.
                    target.Damage(dmg, OffensiveElement, damageType, this);
                }
                else
                {
                    var formula = damage.Formula;
                    var damageType = EnumUtil.ParseEnum<Enums.DamageType>(damage.Type.ToString(), Enums.DamageType.Magical);
                    FormulaParser parser = new FormulaParser(this, castObject, target);
                    var dmg = parser.Eval(formula);
                    target.Damage(dmg, OffensiveElement, damageType, this);
                }
            }
        }
示例#34
0
 public MainTest()
 {
     mParser = new FormulaParser();
 }