pip install openai openpyxl
Create an Excel file questions.xlsx
with a sheet named "Questions" structured like this:
Question | Answer |
---|---|
What is AI? | (empty) |
What is Python? | (empty) |
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!")
Execute the script by running:
python answer_questions.py
You’ve successfully automated answering questions in an Excel sheet using OpenAI’s API!