Extracting text from Word, Excel, CSV and HTML files

Updated · Tested with Python 3.13, python-docx 1.2.0, openpyxl 3.1.5

In short

Use python-docx for Word files, openpyxl for Excel, and Python's own csv and html.parser modules for CSV and HTML. Each has a catch: Word tables are separate from paragraphs, Excel returns numbers without their formatting, CSV depends on the right encoding, and an HTML parser also returns text that CSS hides.

Documents do not all arrive as PDFs. Word files, spreadsheets, CSV exports and saved web pages each need a different library in Python. The samples: company-extract.docx, shipments.xlsx, shipments.csv and company-extract.html.

Word (DOCX)

Shell
pip install python-docx
Python
from docx import Document

document = Document("company-extract.docx")
print([p.text for p in document.paragraphs])
print([[cell.text for cell in row.cells] for table in document.tables for row in table.rows])
Output
['Company extract', 'Harbor Lane Logistics Ltd was registered on 14 March 2019. Its registered office is at 22 Quay Street, Haifa.']
[['Field', 'Value'], ['Company number', '51-482913-6'], ['Status', 'Active'], ['Share capital', '1,250.50']]

The catch: document.paragraphs does not include the text inside tables. Paragraphs and tables are two separate lists, so you lose their order on the page unless you walk the document body yourself. python-docx also reads only .docx; the older .doc format needs converting first.

Excel (XLSX)

Shell
pip install openpyxl
Python
from openpyxl import load_workbook

workbook = load_workbook("shipments.xlsx", read_only=True, data_only=True)
for sheet in workbook.worksheets:
    print(sheet.title, [list(row) for row in sheet.iter_rows(values_only=True)][:2])
Output
Shipments [['Month', 'Containers', 'Average gate minutes'], ['July', 1320, 41]]
Customers [['Customer', 'Contract', 'Share of warehouse'], ['Bayview Holdings Ltd', 'Yearly', 0.2]]

Two settings matter. data_only=True gives you the value a formula last produced instead of the formula itself; it is empty if the file was never opened in Excel after the formula was written. read_only=True keeps memory low on large workbooks. Numbers arrive as numbers, so 0.2 is not the "20%" the sheet may show.

CSV

The standard library is enough.

Python
import csv

with open("shipments.csv", newline="", encoding="utf-8") as f:
    print(list(csv.reader(f))[:2])
Output
[['Month', 'Containers', 'Average gate minutes'], ['July', '1320', '41']]

Everything is text here, including the numbers. The hard part of CSV is the encoding: a file saved by an older system may not be UTF-8, and then accents and Hebrew turn into wrong characters without any error.

HTML

To get the text of a page without its tags, scripts and styles, the standard library's parser will do:

Python
from html.parser import HTMLParser

class Text(HTMLParser):
    def __init__(self):
        super().__init__()
        self.skip, self.out = 0, []

    def handle_starttag(self, tag, attrs):
        if tag in ("script", "style"):
            self.skip += 1

    def handle_endtag(self, tag):
        if tag in ("script", "style"):
            self.skip -= 1

    def handle_data(self, data):
        if not self.skip and data.strip():
            self.out.append(data.strip())

parser = Text()
parser.feed(open("company-extract.html", encoding="utf-8").read())
print(parser.out)
Output
['Company extract', 'Company extract', 'Harbor Lane Logistics Ltd was registered on', '14 March 2019', '.', 'This paragraph is hidden by CSS.', 'Field', 'Value', 'Company number', '51-482913-6', 'Status', 'Active']

Three things to notice. The page title comes out as well as the heading, so "Company extract" appears twice. A sentence with a bold date in it is cut into three pieces. And the paragraph hidden with CSS is still there, because a parser reads the markup, not what a browser would show.

HTML and PDFs through one call

Of the formats in this guide, 100sands reads only HTML, along with PDFs that contain text. It does not read Word, Excel, CSV or plain text files; those are refused with status 415 and the code UNSUPPORTED_FILE, so for them the libraries above are the way.

For the HTML sample, one call returns the text:

Shell
curl https://api.100sands.com/v1/text \
  -H "Authorization: Bearer $SANDS_API_KEY" \
  -F [email protected]

The response has this shape:

JSON
{
  "pages": 1,
  "text": "Company extract\nHarbor Lane Logistics Ltd was registered on 14 March 2019.\n...\nField\tValue\nCompany number\t51-482913-6\nStatus\tActive"
}

Three differences from the parser above. The page title and scripts are left out, so "Company extract" appears once. The sentence with the bold date stays one line. And each table row is one line, with its cells separated by tabs. Like the parser, it reads the markup and not the screen: an element hidden with the hidden attribute or an inline display:none is left out, but one hidden by a rule in a stylesheet, like the paragraph in this sample, is kept.

Questions

How do I read a .docx file in Python?

Install python-docx, open the file with Document(path), and read document.paragraphs for the text and document.tables for the tables. Text inside tables is not in the paragraphs list.

Why does openpyxl return None for a formula cell?

With data_only=True, openpyxl returns the value Excel saved the last time it calculated the sheet. If the file was written by a program and never opened in Excel, no value was saved and you get None.

Can python-docx open old .doc files?

No. It reads only the .docx format. Convert a .doc file first, for example with LibreOffice from the command line.

Try it on your own documents

A free plan every month, no credit card. See the PDF to text API.

Start free