Utilizzo della funzione ICustomFunction

Creazione e valutazione di una funzione definita dall’utente

Questo articolo illustra l’implementazione dell’interfaccia ICustomFunction per scrivere una funzione personalizzata e utilizzarla nel foglio di calcolo per ottenere i risultati. Definiremo una funzione personalizzata per nomeMyFunc che accetterà 2 parametri con i seguenti dettagli.

  • Il primo parametro si riferisce a una singola cella
  • Il secondo parametro si riferisce a un intervallo di celle

La funzione personalizzata aggiungerà tutti i valori dall’intervallo di celle specificato come secondo parametro e dividerà il risultato con il valore nel primo parametro.

Ecco come abbiamo implementato il metodo CalculateCustomFunction.

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
public class CustomFunction : ICustomFunction
{
public object CalculateCustomFunction(string functionName, System.Collections.ArrayList paramsList, System.Collections.ArrayList contextObjects)
{
decimal total = 0M;
try
{
// Get value of first parameter
decimal firstParamB1 = System.Convert.ToDecimal(paramsList[0]);
// Get value of second parameter
Array secondParamC1C5 = (Array)(paramsList[1]);
// get every item value of second parameter
foreach (object[] value in secondParamC1C5)
{
total += System.Convert.ToDecimal(value[0]);
}
total = total / firstParamB1;
}
catch
{
}
// Return result of the function
return total;
}
}

Ecco come utilizzare la funzione appena definita in un foglio di calcolo

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Open the workbook
Workbook workbook = new Workbook();
// Obtaining the reference of the first worksheet
Worksheet worksheet = workbook.Worksheets[0];
// Adding sample values to cells
worksheet.Cells["B1"].PutValue(5);
worksheet.Cells["C1"].PutValue(100);
worksheet.Cells["C2"].PutValue(150);
worksheet.Cells["C3"].PutValue(60);
worksheet.Cells["C4"].PutValue(32);
worksheet.Cells["C5"].PutValue(62);
// Adding custom formula to Cell A1
workbook.Worksheets[0].Cells["A1"].Formula = "=MyFunc(B1,C1:C5)";
// Calcualting Formulas
workbook.CalculateFormula(false, new CustomFunction());
// Assign resultant value to Cell A1
workbook.Worksheets[0].Cells["A1"].PutValue(workbook.Worksheets[0].Cells["A1"].Value);
// Save the file
workbook.Save(dataDir + "UsingICustomFunction_out.xls");

Panoramica

Le API Aspose.Cells inseriscono semplicemente l’oggetto ReferredArea in “paramsList” quando il parametro corrispondente è un riferimento o il risultato calcolato è un riferimento. Se hai bisogno del riferimento stesso, puoi utilizzare direttamente la ReferredArea. Se è necessario ottenere il valore di una singola cella dal riferimento corrispondente alla posizione della formula, è possibile utilizzare il metodo ReferredArea.GetValue(rowOffset, int colOffset). Se hai bisogno di un array di valori di cella per l’intera area, puoi utilizzare il metodo ReferredArea.GetValues.

Siccome le API Aspose.Cells danno la ReferredArea in “paramsList”, la ReferredAreaCollection in “contextObjects” non sarà più necessaria (nelle vecchie versioni non era sempre possibile dare una mappa uno-a-uno ai parametri della funzione custom) quindi è è stato rimosso dai “contextObjects”.

 public object CalculateCustomFunction(string functionName, ArrayList paramsList, ArrayList contextObjects)

{

    ...

    object o = paramsList[i];

    if(o is ReferredArea) //fetch data from reference

    {

        ReferredArea ra = (ReferredArea)o;

        if(ra.IsArea)

        {

            o = ra.GetValues();

        }

        else

        {

            o = ra.GetValue(0, 0);

        }

    }

    if (o is Array)

    {

        ...

    }

    else if...

    ...

}