Search Tutorials
--Ads--Loading Excel, PowerPoint and XML Files
Extract text, tables and structure from Excel workbooks, PowerPoint decks and XML files for RAG.
Company knowledge does not live only in PDFs and Word files. Price lists and trackers live in Excel workbooks, training and strategy material in PowerPoint decks, and system exports and configuration in XML. This lesson shows how to extract text and structure from each format into the Document objects used in Loading PDF, DOCX, HTML, Markdown, CSV and JSON.
What you will learn
- How to load Excel workbooks with openpyxl and pandas, sheet by sheet
- How to extract slide text, tables and speaker notes from PowerPoint files
- How to turn XML records into readable text
- How to choose a representation that retrieves well
Prerequisites
Installation
pip install openpyxl pandas python-pptx lxml
The shared Document class
from dataclasses import dataclass, field
from pathlib import Path
@dataclass
class Document:
text: str
metadata: dict = field(default_factory=dict)
Excel workbooks
An Excel file has several sheets, and each sheet is a table. There are two useful representations:
- Row records: one document per row, written as "column: value" lines. Best when each row is a self-contained item (a product, an employee grade, a ticket).
- Markdown table chunks: groups of rows with the header repeated. Best for reference tables people read as a whole (Table-Aware RAG).
import pandas as pd
def load_excel_rows(path: Path, max_rows_per_sheet: int = 10_000) -> list[Document]:
"""One document per row, for record-like sheets."""
docs = []
sheets = pd.read_excel(path, sheet_name=None, dtype=str) # dict: sheet name -> DataFrame
for sheet, df in sheets.items():
df = df.dropna(how="all").fillna("")
for i, row in df.head(max_rows_per_sheet).iterrows():
lines = [f"{col}: {val}" for col, val in row.items() if str(val).strip()]
if lines:
docs.append(Document("\n".join(lines),
{"source": str(path), "type": "xlsx", "sheet": sheet, "row": int(i) + 2}))
return docs
def load_excel_tables(path: Path, rows_per_chunk: int = 25) -> list[Document]:
"""Markdown table chunks with the header repeated, for reference tables."""
docs = []
for sheet, df in pd.read_excel(path, sheet_name=None, dtype=str).items():
df = df.dropna(how="all").fillna("")
for start in range(0, len(df), rows_per_chunk):
part = df.iloc[start:start + rows_per_chunk]
table = part.to_markdown(index=False) # needs: pip install tabulate
docs.append(Document(f"Sheet: {sheet} (rows {start + 2}-{start + len(part) + 1})\n{table}",
{"source": str(path), "type": "xlsx", "sheet": sheet}))
return docs
Row numbers in metadata start at 2 because row 1 holds the headers, so citations point to the row users see in Excel.
pandas and openpyxl.load_workbook(path, data_only=True) read the values Excel last calculated and saved. A file generated by a script that never opened in Excel may have empty values for formula cells.
For aggregate questions ("total sales in Q3"), do not rely on retrieved rows: load the sheet into pandas or SQL and compute (Question Answering over Excel and CSV Files).
PowerPoint decks
Each slide makes a natural chunk. Extract the title, body text, tables and the speaker notes, which often contain the real explanation behind terse bullet points.
from pptx import Presentation
def load_pptx(path: Path) -> list[Document]:
deck = Presentation(path)
docs = []
for number, slide in enumerate(deck.slides, start=1):
title = slide.shapes.title.text.strip() if slide.shapes.title is not None else ""
parts = []
for shape in slide.shapes:
if shape.has_text_frame and shape != slide.shapes.title:
text = "\n".join(p.text for p in shape.text_frame.paragraphs if p.text.strip())
if text:
parts.append(text)
if shape.has_table:
rows = [" | ".join(cell.text.strip() for cell in row.cells) for row in shape.table.rows]
parts.append("\n".join(rows))
notes = ""
if slide.has_notes_slide:
notes = slide.notes_slide.notes_text_frame.text.strip()
body = "\n".join(parts)
text = f"Slide {number}: {title}\n{body}" + (f"\nSpeaker notes: {notes}" if notes else "")
if body or notes:
docs.append(Document(text, {"source": str(path), "type": "pptx", "slide": number, "title": title}))
return docs
Charts and images on slides are not extracted as text. For visually heavy decks, render slides to images and describe them with a vision model (RAG over Images and Charts).
XML files
XML exports usually contain repeated records (products, articles, tickets). Turn each record element into readable "path: value" text:
from lxml import etree
def element_to_lines(el, prefix: str = "") -> list[str]:
tag = etree.QName(el).localname # drop namespaces for readability
path = f"{prefix}{tag}"
lines = []
if el.text and el.text.strip():
lines.append(f"{path}: {el.text.strip()}")
for name, value in el.attrib.items():
lines.append(f"{path}@{etree.QName(name).localname}: {value}")
for child in el:
if isinstance(child.tag, str): # skip comments and processing instructions
lines.extend(element_to_lines(child, f"{path}."))
return lines
def load_xml(path: Path, record_tag: str) -> list[Document]:
parser = etree.XMLParser(resolve_entities=False, no_network=True) # safe against XXE attacks
tree = etree.parse(str(path), parser)
records = tree.getroot().iter(f"{{*}}{record_tag}")
return [Document("\n".join(element_to_lines(r)), {"source": str(path), "type": "xml", "record": i})
for i, r in enumerate(records)]
# docs = load_xml(Path("products.xml"), record_tag="product")
Never parse untrusted XML with external entity resolution enabled. The parser settings above block XML External Entity (XXE) attacks, which can read local files.
Common errors and troubleshooting
ImportError: Missing optional dependency 'tabulate':to_markdown()needspip install tabulate.- Old
.xlsor.pptfiles: openpyxl and python-pptx read only the modern.xlsxand.pptxformats. Convert old files first (for example with LibreOffice in headless mode). - Dates appear as numbers: Excel stores dates as serial numbers; read with pandas without
dtype=strfor date columns, or convert explicitly. - Merged cells in Excel produce empty values in all but the first cell; fill them forward with
df.ffill()where appropriate.
Key takeaways
- Excel: one document per row for records, Markdown table chunks for reference tables; compute aggregates with pandas or SQL.
- PowerPoint: one document per slide, including tables and speaker notes.
- XML: one document per record element, flattened to "path: value" lines, parsed safely.
- Keep sheet, row and slide numbers in metadata for precise citations.
Frequently asked questions
Can a library handle all formats for me?
Yes: Unstructured, Docling and framework loaders (LangChain, LlamaIndex) support Office formats (Layout-Aware Parsers). Writing small loaders yourself gives full control over the representation.
Should I index every row of a huge spreadsheet?
Only if questions target individual rows. For analytics, keep data in a database and use Text-to-SQL.
Practice exercises
- Load a workbook with two sheets and compare retrieval with row documents vs table chunks for five questions.
- Extend
load_pptxto skip slides whose title is "Agenda" or "Thank you".