Question Answering over Excel and CSV Files

Answer questions about spreadsheets by combining row retrieval with pandas or SQL for calculations.

Last Updated:

Module 7 · Lesson 7 of 8 · Intermediate

Question Answering over Excel and CSV Files

Answer questions about spreadsheets by combining row retrieval with pandas or SQL for calculations.

"Which region had the highest sales in Q3?" "How many tickets are still open for customer ACME?" "What is the hotel limit for grade L4 in Mumbai?" Spreadsheet questions come in two kinds: lookups (find the right row) and calculations (filter, group, sum, count). Vector search handles lookups well and calculations badly. This lesson builds a spreadsheet assistant that uses retrieval for lookups and code for calculations.

What you will learn

  • Why embedding rows fails for aggregate questions
  • How to answer lookup questions with row-level retrieval
  • How to answer calculation questions by generating and running SQL over the spreadsheet
  • How to route between the two safely

Prerequisites

pip install pandas openpyxl anthropic pydantic numpy sentence-transformers

Sample data

import pandas as pd

sales = pd.DataFrame({
    "order_id": [1001, 1002, 1003, 1004, 1005, 1006],
    "region": ["North", "South", "North", "West", "South", "West"],
    "product": ["Router X200", "Router X100", "Switch S10", "Router X200", "Switch S10", "Router X100"],
    "quarter": ["Q3", "Q3", "Q3", "Q4", "Q3", "Q3"],
    "amount_inr": [45000, 32000, 18000, 51000, 21000, 30000],
})
sales.to_excel("sales.xlsx", index=False)

Why row retrieval fails for calculations

To answer "total Q3 sales in the South", a model needs every South Q3 row. Top-k retrieval returns the k most similar rows, which may miss some and include others, and then the model has to add numbers in its head. For a real sheet with thousands of rows the answer will be wrong. Calculations belong in code.

Part 1: Calculations with SQL over the sheet

Load the sheet into an in-memory SQLite database, give the model the schema with sample values, and let it write a single SELECT. Validate and run it read-only.

sheet_qa.py
import re
import sqlite3
from typing import Literal

import anthropic
import numpy as np
import pandas as pd
from pydantic import BaseModel
from rag_helpers import ask, embed

client = anthropic.Anthropic()
df = pd.read_excel("sales.xlsx")
db = sqlite3.connect(":memory:")
df.to_sql("sales", db, index=False)

def describe(df: pd.DataFrame) -> str:
    cols = [f"- {c} ({df[c].dtype}); examples: {', '.join(map(str, df[c].dropna().unique()[:4]))}"
            for c in df.columns]
    return "Table sales:\n" + "\n".join(cols)

class SqlPlan(BaseModel):
    sql: str

def sql_answer(question: str) -> str:
    plan = client.messages.parse(
        model="claude-opus-5-5", max_tokens=1000, output_config={"effort": "medium"},
        system=f"Write one SQLite SELECT statement for this table.\n{describe(df)}",
        messages=[{"role": "user", "content": question}], output_format=SqlPlan).parsed_output
    sql = plan.sql.strip().rstrip(";")
    if not re.match(r"(?is)^\s*select\b", sql) or ";" in sql or re.search(
            r"(?i)\b(insert|update|delete|drop|alter|attach|pragma)\b", sql):
        return "Sorry, I could not build a safe query for that question."
    rows = db.execute(sql).fetchmany(50)
    cols = [c[0] for c in db.execute(sql).description]
    table = "\n".join([" | ".join(cols)] + [" | ".join(map(str, r)) for r in rows])
    return ask(f"Question: {question}\nSQL: {sql}\nResult:\n{table}\n\n"
               "Answer from the result only. Format amounts in rupees.")

print(sql_answer("What were total Q3 sales in the South region?"))
Total Q3 sales in the South region were ?53,000 (orders 1002 and 1005).

The database is in memory and built from the file, so the model's SQL cannot change the original spreadsheet; the keyword check is an extra safety layer.

Part 2: Lookups with row retrieval

For "Which region bought order 1004?" or fuzzy questions ("the big router order in the West"), embed each row as "column: value" text and retrieve:

row_texts = ["\n".join(f"{c}: {v}" for c, v in row.items()) for _, row in df.iterrows()]
row_vectors = embed(row_texts)

def lookup_answer(question: str, k: int = 3) -> str:
    scores = row_vectors @ embed(question, query=True)[0]
    rows = "\n\n".join(row_texts[i] for i in np.argsort(-scores)[:k])
    return ask(f"Rows:\n{rows}\n\nAnswer from these rows only: {question}")

Part 3: Route each question

class Route(BaseModel):
    kind: Literal["calculation", "lookup"]

def answer(question: str) -> str:
    route = client.messages.parse(
        model="claude-opus-5-5", max_tokens=200, output_config={"effort": "low"},
        system="Classify the question about a spreadsheet. 'calculation' needs totals, counts, "
               "averages, rankings or filters over many rows; 'lookup' asks about specific rows.",
        messages=[{"role": "user", "content": question}], output_format=Route).parsed_output
    return sql_answer(question) if route.kind == "calculation" else lookup_answer(question)

for q in ["Which product sold most in Q3 by amount?", "What did order 1004 contain?"]:
    print(q, "->", answer(q))
Which product sold most in Q3 by amount? -> Router X100 had the highest Q3 sales at ?62,000.
What did order 1004 contain? -> Order 1004 was a Router X200 sold in the West in Q4 for ?51,000.

Common errors and troubleshooting

  • Column names with spaces: rename columns to snake_case before loading into SQLite, or the model must quote them.
  • Wrong categories in SQL ("south" vs "South"): include example values in the schema description, as describe() does.
  • Dates stored as text: convert date columns with pd.to_datetime before to_sql.
  • Huge results: cap rows (fetchmany) and ask for aggregates instead of full listings.

Key takeaways

  • Use code (SQL or pandas) for totals, counts and rankings; never ask the model to add up retrieved rows.
  • Use row retrieval for lookups and fuzzy questions about specific records.
  • Route each question, validate generated SQL, and run it on a read-only copy.

Frequently asked questions

Can the model write pandas code instead of SQL?

Yes, but executing arbitrary generated Python is riskier than a validated SELECT. If you do it, run it in a sandbox (for example a server-side code execution tool).

What about very large sheets?

Load them into a real database and treat them as structured data (SQL and Data Warehouse Assistant).

Practice exercises

  1. Add a CSV loader and a second table, and let the model join them.
  2. Show the generated SQL under each answer so users can check it.

Related tutorials