Using OpenAI API to Answer Questions in an Excel Sheet

Prerequisites

  • An OpenAI API key (Get one from OpenAI)
  • Python installed on your computer
  • Install required libraries by running:
pip install openai openpyxl

Step 1: Set Up Your Excel File

Create an Excel file questions.xlsx with a sheet named "Questions" structured like this:

QuestionAnswer
What is AI?(empty)
What is Python?(empty)

Step 2: Write the Python Script

import openai
import openpyxl

openai.api_key = "your-api-key-here"

file_path = "questions.xlsx"
wb = openpyxl.load_workbook(file_path)
sheet = wb["Questions"]

for row in sheet.iter_rows(min_row=2, max_col=1, values_only=False):
        question_cell = row[0]
        answer_cell = sheet.cell(row=question_cell.row, column=2)

        if question_cell.value and not answer_cell.value:
                try:
                        response = openai.ChatCompletion.create(
                                model="gpt-3.5-turbo",
                                messages=[{"role": "user", "content": question_cell.value}]
                        )
                        answer_cell.value = response["choices"][0]["message"]["content"]
                except Exception as e:
                        answer_cell.value = f"Error: {str(e)}"

wb.save(file_path)
print("Answers saved to Excel!")

Step 3: Run the Script

Execute the script by running:

python answer_questions.py

Conclusion

You’ve successfully automated answering questions in an Excel sheet using OpenAI’s API!