Python xlrd and xlwt Tutorial: Reading and Writing Excel Files
This tutorial introduces nine Python libraries for Excel manipulation, compares xlrd and xlwt, shows how to install them, demonstrates core functions for reading sheets, rows, columns, and cells with xlrd, and provides detailed examples of creating, formatting, merging, and styling Excel files using xlwt.
This article begins with a comparison of nine Python libraries capable of handling Excel files, highlighting xlrd for reading and xlwt for writing.
xlrd (reading)
Installation can be done via pip install xlrd or using Anaconda, which often includes the package already.
Key functions include opening a workbook with xlrd.open_workbook(filename) , accessing sheets by index or name, and retrieving rows, columns, and cell values using methods such as sheet.row(rowx) , sheet.col(colx) , and sheet.cell_value(rowx, colx) . An example script reads a sample workbook, prints a specific cell value, the total number of rows, and extracts a column into a list.
xlwt (writing)
Install with pip install xlwt . The library creates new .xls files (Excel 97‑2003 format). A typical workflow creates a workbook with xlwt.Workbook() , adds a sheet via workbook.add_sheet('SheetName') , and writes data using sheet.write(row, col, 'content') .
Formatting examples cover:
Setting fonts (bold, underline, italic) with xlwt.Font() and applying via XFStyle() .
Adjusting column width using sheet.col(col_index).width = 256 * width_in_chars .
Setting row height through style xlwt.easyxf('font:height 360;') and applying to rows.
Merging cells with sheet.write_merge(row_start, row_end, col_start, col_end, 'text') .
Adding borders by configuring xlwt.Borders() and assigning to a style.
Applying background colors via xlwt.Pattern() and setting pattern.pattern_fore_colour .
Aligning content using xlwt.Alignment() with horizontal and vertical options.
Each formatting example concludes with workbook.save('new_file.xls') to generate the final Excel file.
The article also provides links to official documentation for both libraries and additional learning resources such as list comprehensions and Python tutorials.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.