如何在excel里使用chatgpt的api有excel使用的vba代码吗
要在Excel中使用ChatGPT的API,您需要编写一个VBA宏来调用API并将响应解析为Excel电子表格。以下是一个简单的示例代码,它使用ChatGPT的API,您需要将其中的API密钥和请求URL替换为您自己的。
Sub ChatGPTAPI()
Dim APIKey As String
Dim RequestURL As String
Dim InputText As String
Dim ResponseText As String
' Set your ChatGPT API key and request URL
APIKey = "YOUR_API_KEY"
RequestURL = "https://api.openai.com/v1/engines/davinci-codex/completions"
' Get input text from cell A1
InputText = Range("A1").Value
' Send a request to ChatGPT API
Dim HttpReq As Object
Set HttpReq = CreateObject("WinHttp.WinHttpRequest.5.1")
HttpReq.Open "POST", RequestURL, False
HttpReq.setRequestHeader "Content-Type", "application/json"
HttpReq.setRequestHeader "Authorization", "Bearer " & APIKey
HttpReq.send ("{""prompt"":""" & InputText & """,""max_tokens"":150,""n"":1,""stop"":""\n""}")
' Parse the response JSON and get the generated text
Dim JSON As Object
Set JSON = JsonConverter.ParseJson(HttpReq.responseText)
ResponseText = JSON("choices")(0)("text")
' Output the generated text to cell A2
Range("A2").Value = ResponseText
End Sub
您需要在Excel VBA编辑器中引用JSON解析器库,以便能够解析响应JSON。您可以使用VBA-JSON解析器库,该库提供了一个名为JsonConverter的对象,可用于解析和生成JSON。
为了使用该库,您需要将VBA-JSON.bas文件导入到您的Excel工作簿中,并在VBA编辑器中添加对该文件的引用。然后,您可以使用JsonConverter对象的ParseJson方法来解析JSON字符串,并使用JsonConverter对象的ToString方法来生成JSON字符串。
原文地址: https://www.cveoy.top/t/topic/GuC 著作权归作者所有。请勿转载和采集!