Overview
Standard Excel formulas address a variety of business requirements. Of course, like anything else in life, there are times when your enterprise will require additional capabilities to address a specific use case.
When it comes to spreadsheet calculations, user-defined formulas offer a variety of options for those who wish to introduce custom, task-specific calculations within Excel documents. User-defined formulas allow you to automate repetitive tasks, analyze data more efficiently, and execute advanced calculations not possible with built-in functions.
By integrating AI services, we can take Excel formula calculations to a whole new level. We can analyze large datasets more efficiently, incorporate pattern recognition, make predictions, and so much more.
In this blog post, I will incorporate a user-defined formula using the DevExpress WinForms Spreadsheet Control and illustrate how to utilize AI for advanced calculations.
Implementing User-Defined Formulas within the DevExpress WinForms Spreadsheet Control
In the following sections, I'll create a user-defined formula that uses AI services for spreadsheet calculations. Feel free to use my example as a starting point and if you encounter issues, please submit a ticket via the DevExpress Support Center. We'll be happy to follow up.
Step 1: Setting Up the DevExpress WinForms Spreadsheet Control
First, I'll need to add the DevExpress WinForms Spreadsheet Control to my project. If you are new to our WinForms product line (or the Spreadsheet Control), please follow our Spreadsheet: Getting Started guide.
Step 2: Setting Up the OpenAI Client
Once I've added the Spreadsheet Control to my project, I can install the Azure.AI.OpenAI NuGet package and create a class to register OpenAIClient
. This client will be used in the custom formula class (to send requests to the AI service).
public static class AIFormulaClient
{
public static OpenAIClient Client;
static AIFormulaClient() => Client = new OpenAIClient("your OpenAI key");
}
Step 3: Creating a User-Defined Function
Next, I'll create a user-defined function (UDF) within my sample WinForms application. For purposes of this example, I'll define a function called AISummary. This function uses the AI service to generate a summary for a selected cell range.
The AISummaryFunction
class implements the custom function and provides two parameters:
- the first is a required parameter (specifies source cell range for the summary)
- the second is an optional parameter used to set summary length in words.
The IFunction.Evaluate
method retrieves parameter values and sends cell data (in CSV format) and the word count to the GetSummary
method. This method generates a request using OpenAIClient
and returns the response. The returned value (AI-generated summary) is used as the result of the formula evaluation.
public class AISummaryFunction : ICustomFunction
{
const string functionName = "AISummary";
readonly ParameterInfo[] functionParameters;
public AISummaryFunction()
{
this.functionParameters = new ParameterInfo[] {
new ParameterInfo(ParameterType.Reference, ParameterAttributes.Required),
new ParameterInfo(ParameterType.Value, ParameterAttributes.Optional) };
}
public string Name { get { return functionName; } }
ParameterInfo[] IFunction.Parameters { get { return functionParameters; } }
ParameterType IFunction.ReturnType { get { return ParameterType.Value; } }
bool IFunction.Volatile { get { return false; } }
ParameterValue IFunction.Evaluate(IList<ParameterValue> parameters, EvaluationContext context)
{
int wordCount = 40;
if (parameters.Count > 1)
wordCount = (int)parameters[1].NumericValue;
IWorkbook workbook = context.Sheet.Workbook;
workbook.Options.Export.Csv.Range = parameters[0].RangeValue.GetReferenceA1();
byte[] cellDataBytes = workbook.SaveDocument(DocumentFormat.Csv);
string value = GetSummary(Encoding.UTF8.GetString(cellDataBytes), wordCount);
return value;
}
string GetSummary(string cellRangeData, int wordCount)
{
ChatCompletionsOptions chatCompletionsOptions = new ChatCompletionsOptions()
{
DeploymentName = "gpt-4-vision-preview",
Messages =
{
new ChatRequestSystemMessage("You are a helpful assistant."),
new ChatRequestUserMessage(
new ChatMessageTextContentItem(string.Format("Please create summary in {0} words for the following excel data", wordCount)),
new ChatMessageTextContentItem(cellRangeData))
},
MaxTokens = 300
};
Response<ChatCompletions> chatResponse = AIFormulaClient.Client.GetChatCompletions(chatCompletionsOptions);
ChatChoice choice = chatResponse.Value.Choices[0];
return choice.Message.Content;
}
string IFunction.GetName(CultureInfo culture)
{
return functionName;
}
}
Step 4: Registering the Custom Function
In this step, I'll register the custom function.
public Form1()
{
InitializeComponent();
AISummaryFunction aiSummaryFunction = new AISummaryFunction();
var globalFunctions = spreadsheetControl.Document.Functions.GlobalCustomFunctions;
if (!globalFunctions.Contains(aiSummaryFunction.Name))
globalFunctions.Add(aiSummaryFunction);
}
Step 5: Using the Custom Function within the Spreadsheet
I can now use the AISummary function in my spreadsheet (just like any other formula). I'll load my Excel file in the WinForms Spreadsheet Control or I can enter data for the summary into a cell range then apply the AISummary function to obtain my AI-generated summary.
Worksheet worksheet = spreadsheetControl.ActiveWorksheet;
worksheet["E2"].Formula = "AISummary(A2:D10, 50)";
Step 6: Testing
Of course, we can't forget testing...I'll test my new user-defined formula and ensure my AI integration/custom formulas work as expected.
Your Feedback Matters
As always, your feedback is very important. Please let us know whether additional AI-related samples/solutions are of interest to you and how you expect AI to change your development strategies in the next 12-months.