Set Up OpenAI API Key
- Go to the OpenAI Platform to create an account or log in.
- Navigate to the API section to obtain your API key. This key will be used to authenticate your requests to OpenAI.
Enable Developer Tools in Excel
- Open Microsoft Excel and access the Excel Options by clicking on "File" > "Options".
- Select "Customize Ribbon" and enable the "Developer" option. This adds the Developer tab to Excel's toolbar, allowing you to insert macros and scripts.
Install Power Query and Power Query SDK
- Ensure that Power Query is installed in your version of Excel. It typically comes built-in with Excel 2016 and later.
- Install the Power Query SDK to enable advanced querying and data manipulation.
Create a Power Query Script to Call OpenAI
-
Open the Power Query Editor by selecting "Data" > "Get Data" > "Launch Power Query Editor".
-
Create a new blank query in which you will write the script to call the OpenAI API.
- Enter the following Power Query M script to access OpenAI using your API key:
let
apiKey = "YOUR_API_KEY",
smallBusinessDescription = "YOUR_PROMPT_OR_INPUT",
url = "https://api.openai.com/v1/engines/davinci-codex/completions",
body =
"{" &
"""prompt"":""" & smallBusinessDescription & """," &
"""max_tokens"":100" &
"}",
source = Json.Document(Web.Contents(url,
[
Headers=[
#"Content-Type"="application/json",
#"Authorization"="Bearer "&apiKey
],
Content=Text.ToBinary(body)
]))
in
source
Retrieve and Use Data in Excel
-
After executing the query, retrieve the output from OpenAI in a structured format by transforming the JSON response into a table.
-
Load the data back into Excel for manipulation and analysis by clicking on "Close & Load" within the Power Query Editor.
Automate the Query with VBA (Optional)
- For automation, use VBA to refresh the query or send different requests to OpenAI. Access the Developer tab and click on "Visual Basic".
- Insert a new module and write a macro to automate the data retrieval process:
Sub RefreshOpenAIQuery()
ThisWorkbook.Connections("Query - YourQueryName").Refresh
End Sub
Test and Iterate
- Run your macro to ensure data is fetched from OpenAI and loads correctly into Excel.
- Iteratively refine your query and VBA code to suit your specific use case.