Scroll to Top
💻
Free Code
Users get ready-to-use code at no cost.
📋
Easy Copy
Copy and use the code instantly.
Quick Learning
Understand concepts fast and clearly.
📝
Step-by-Step
Follow simple instructions to implement.
📅 August 14, 2024 💻 Tutorial ⭐ Beginner Friendly

Automate Google Sheets Like a Pro with AI

Author Avatar

Ashish Dwivedi

Editorial Team • Tech Writer

About This Tutorial

Automate Google Sheets like a pro with AI by integrating ChatGPT using a free Apps Script. Input prompts directly in cells and get instant AI-generated responses. From writing, summarizing, to data analysis—boost productivity, reduce manual work, and turn your spreadsheet into a smart assistant for everyday tasks.
  1. Step 1: Click on the Copy button to copy the code snippet.
  2. Step 2: Paste the copied code into your project’s script editor.

Apps Scripts Blog

Read Blog

📂 javascript
⚡ script1.js
⚡ script1.js
function onOpen() {
  const ui = SpreadsheetApp.getUi();
  ui.createMenu('OUTRIGHT')
    .addItem('Generate Answers', 'generateAnswersForQuestions')
    .addItem('Set API Key', 'showSidebar')
    .addToUi();

  createHeader();
  checkApiKey();
}

// Create header row
function createHeader() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  const headers = ["Question", "Answer"];
  const headerRange = sheet.getRange('A1:B1');
  headerRange.setValues([headers]);
  headerRange.setFontWeight("bold");
  headerRange.setFontSize(12);
}

// Show sidebar for entering API key
function showSidebar() {
  const html = HtmlService.createHtmlOutputFromFile('Sidebar')
    .setTitle('Set API Key')
    .setWidth(300);
  SpreadsheetApp.getUi().showSidebar(html);
}

// Check if API key is set
function checkApiKey() {
  const apiKey = PropertiesService.getUserProperties().getProperty('OPENAI_API_KEY');
  if (!apiKey) {
    showSidebar();
    SpreadsheetApp.getUi().alert('Please set your API key using the sidebar.');
  }
}

// Save API key to user properties
function saveApiKey(apiKey) {
  PropertiesService.getUserProperties().setProperty('OPENAI_API_KEY', apiKey);
}

// Generate answers for questions in column A
function generateAnswersForQuestions() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  const lastRow = sheet.getLastRow();

  const questionsRange = sheet.getRange('A2:A' + lastRow);
  const questions = questionsRange.getValues();

  const responsesRange = sheet.getRange('B2:B' + lastRow);
  const existingResponses = responsesRange.getValues();

  questions.forEach((question, index) => {
    if (question[0] && !existingResponses[index][0]) {
      const prompt = `Generate a response for the following question: "${question}"`;
      const response = getChatGPTResponse(prompt);

      if (response) {
        sheet.getRange('B' + (index + 2)).setValue(response.trim());
      } else {
        Logger.log('Failed to get a response for question: ' + question);
      }
    } else {
      Logger.log('Response already exists for question: ' + question);
    }
  });
}

// Fetch response from ChatGPT
function getChatGPTResponse(prompt) {
  const apiKey = PropertiesService.getUserProperties().getProperty('OPENAI_API_KEY');
  if (!apiKey) {
    Logger.log('API key not set.');
    return null;
  }

  const url = 'https://api.openai.com/v1/chat/completions';
  const payload = {
    model: "gpt-3.5-turbo",
    messages: [
      { role: "system", content: "I am your lovely assistant" },
      { role: "user", content: prompt }
    ]
  };

  const options = {
    method: 'post',
    payload: JSON.stringify(payload),
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ' + apiKey
    }
  };

  try {
    const response = UrlFetchApp.fetch(url, options);
    const data = JSON.parse(response.getContentText());
    return data.choices[0].message.content.trim();
  } catch (e) {
    Logger.log('Error: ' + e);
    return null;
  }
}