你好!
通过自定义公式可以实现该需求,具体代码如下:
- public partial class MainPage : UserControl
- {
- public MainPage()
- {
- InitializeComponent();
- gcSpreadSheet1.Sheets[0].Cells[0, 1].Value = 1;
- gcSpreadSheet1.Sheets[0].Cells[1, 1].Value = 2;
- gcSpreadSheet1.Sheets[0].Cells[2, 1].Value = 3;
- gcSpreadSheet1.Sheets[0].Cells[3, 1].Value = 9;
- gcSpreadSheet1.Sheets[0].Cells[0, 2].Value = 5;
- gcSpreadSheet1.Sheets[0].Cells[1, 2].Value = 6;
- gcSpreadSheet1.Sheets[0].Cells[2, 2].Value = 7;
- gcSpreadSheet1.Sheets[0].Cells[3, 2].Value = 5;
- gcSpreadSheet1.AddCustomFunction(new CalcCSLOPEFunctionInfo());
- gcSpreadSheet1.AddCustomFunction(new CLNFunctionInfo());
- gcSpreadSheet1.Sheets[0].SetFormula(0, 0, "CSLOPE(B1:B4,CLN(C1:C4))");
- }
- }
- public class CalcCSLOPEFunctionInfo : GrapeCity.CalcEngine.Functions.CalcSlopeFunction
- {
- public override string Name
- {
- get
- {
- return "CSLOPE";
- }
- }
- public override object Evaluate(object[] args)
- {
- // 将第二个参数封装成 CCalcArray 类型,并传作为调用基类 Evaluate 方法的参数
- if (args[1] is object[,])
- {
- CCalcArray array = new CCalcArray(args[1] as object[,]);
- args[1] = array;
- }
- return base.Evaluate(args);
- }
- }
- public class CLNFunctionInfo : GrapeCity.CalcEngine.Functions.CalcFunction
- {
- public override string Name
- {
- get
- {
- return "CLN";
- }
- }
- public override object Evaluate(object[] args)
- {
- if (args[0] is CalcReference)
- {
- // 如果传递的是单元格范围的引用,使用使用以下方法进行计算
- CalcReference array = (CalcReference)args[0];
- int rowCount = array.GetRowCount(0);
- int columnCount = array.GetColumnCount(0);
- object[,] result = new object[rowCount, columnCount];
- for (int i = 0; i < rowCount; i++)
- {
- for (int j = 0; j < columnCount; j++)
- {
- object value = array.GetValue(0, i, j);
- if (value is CalcError)
- {
- result[i, j] = value;
- }
- else
- {
- result[i, j] = Math.Log(Convert.ToDouble(value.ToString()));
- }
- }
- }
- return result;
- }
- else
- {
- return Math.Log(Convert.ToDouble(args[0].ToString()));
- }
- }
- public override int MaxArgs
- {
- // 最多接收一个单元格引用范围
- get { return 1; }
- }
- public override int MinArgs
- {
- // 至少需要一个单元格引用范围
- get { return 1; }
- }
- public override bool AcceptsReference(int i)
- {
- // 允许接收单元格引用的参数类型
- return true;
- }
- }
- // 自定义 CalcArray 类型
- public class CCalcArray : CalcArray
- {
- object[,] items;
- public CCalcArray(object[,] items)
- {
- this.items = (object[,])items.Clone();
- }
- public override int RowCount
- {
- get { return items.GetLength(0); }
- }
- public override int ColumnCount
- {
- get { return items.GetLength(1); }
- }
- public override object GetValue(int row, int column)
- {
- return items[row, column];
- }
- }
复制代码
源码下载:
6847_Formula.zip
(7.46 KB, 下载次数: 983)
|