Using OpenAI in Excel and Google Sheets
Using OpenAI in Excel and Google Sheets
Integrating OpenAI’s GPT models into Excel or Google Sheets can unlock powerful automation and language processing capabilities. This blog post demonstrates how to use OpenAI’s API to translate text in a spreadsheet cell into French using a script.
Google Spreadsheet Apps Script Example
The following script uses OpenAI’s GPT-3.5-turbo model to translate the content of a selected cell into French and outputs the result in the adjacent cell.
Code Example
async function main(workbook: ExcelScript.Workbook) {
// Get the active cell and worksheet.
let selectedCell = workbook.getActiveCell();
let selectedSheet = workbook.getActiveWorksheet();
// Get the text content of the selected cell.
let cellText = selectedCell.getValues()[0][0];
// Define the chatAPI function within the main function.
async function chatAPI(cellText: string): Promise<string> {
const url = "https://api.openai.com/v1/chat/completions";
const apiKey = "API Key"; // Replace with your OpenAI API key
const requestOptions: RequestInit = {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + apiKey,
},
body: JSON.stringify({
"model": "gpt-3.5-turbo",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": cellText + " in French is:"
}
]
}),
};
try {
const response: Response = await fetch(url, requestOptions);
const data: { choices: { message: { content: string } }[] } = await response.json();
const message: string = data.choices[0].message.content; // Accessing the response content
return message;
} catch (error) {
console.log("Error fetching data:", error);
throw error;
}
}
// Call the chatAPI function with the cell text.
try {
const response = await chatAPI(cellText.toString());
// Insert the response into the adjacent cell.
const targetCell = selectedSheet.getCell(selectedCell.getRowIndex(), selectedCell.getColumnIndex() + 1);
targetCell.setValues([[response]]);
} catch (error) {
// Handle errors here, e.g., log or display an error message.
console.log("Error:", error);
}
}
The same can be applied to Google Spreadsheet