1)调用JS计算方法(不推荐,效率低)
MSScriptControl.ScriptControl scriptControl = new MSScriptControl.ScriptControl(); scriptControl.Language = "JScript"; string value = scriptControl.Eval("1+2*(4-3)").ToString(); Console.WriteLine(value);
2)使用DataTable的Compute()方法
DataTable table = new DataTable(); string value = table.Compute("1+2*(4-3)", "").ToString(); Console.WriteLine(value);
3)构建DataTable,给列名添加公式
//计算公式 string expression1 = "a+b*(c-d)"; string expression2 = "a+b-c-d"; //构建table DataTable table = new DataTable(); table.Columns.Add("a", typeof(int)); table.Columns.Add("b", typeof(int)); table.Columns.Add("c", typeof(int)); table.Columns.Add("d", typeof(int)); table.Columns.Add("e1", typeof(int));//公式列 table.Columns.Add("e2", typeof(int));//公式列 //添加公式 table.Columns["e1"].Expression = expression1; table.Columns["e2"].Expression = expression2; //添加一行并赋值 DataRow row = table.Rows.Add(); row["a"] = 1; row["b"] = 2; row["c"] = 4; row["d"] = 3; table.BeginLoadData(); table.EndLoadData(); for (int i = 0; i < table.Columns.Count; i++) { Console.Write(table.Columns[i].ColumnName + "\t"); } Console.WriteLine(); for (int i = 0; i < table.Columns.Count; i++) { Console.Write(row[i].ToString() + "\t"); }