xlutils
xlutils is a Python package offering various utilities for working with Excel files, specifically those compatible with `xlrd` and `xlwt`. It provides functionalities like copying `xlrd.Book` objects to `xlwt.Workbook` objects (xlutils.copy), displaying information, filtering, finding data margins, saving, and handling styles. The current version is 2.0.0. The library, along with its core dependencies `xlrd` and `xlwt`, is considered to be in maintenance mode or archived, with infrequent updates.
Warnings
- breaking xlrd version 2.0.0 and later no longer supports `.xlsx` files due to security vulnerabilities related to parsing. Since `xlutils` relies on `xlrd` for reading, it is effectively limited to `.xls` files for input. Attempting to open an `.xlsx` file will result in an error.
- deprecated xlutils, xlrd, and xlwt are largely unmaintained or in archive status on GitHub. `xlrd` itself advises users to use `openpyxl` for modern Excel file formats (`.xlsx`). It is recommended to use `openpyxl` for new projects or when working with `.xlsx` files.
- gotcha Directly copying cell style information from an `xlrd.Book` object to an `xlwt.Workbook` object is complex. `xlrd` and `xlwt` use different internal representations for cell formatting (`XF` objects). While `xlutils.copy` attempts to preserve basic formatting, detailed style manipulation often requires using `xlutils.filter` with custom logic or a specific workaround.
- gotcha When writing to an Excel sheet using `xlwt` (and by extension `xlutils.copy`), column indices are limited to a range of 0-255 (corresponding to columns A through IV in Excel 2003 `.xls` format). Attempting to write to a column index outside this range will raise a `ValueError`.
Install
-
pip install xlutils
Imports
- copy
from xlutils.copy import copy
- XLRDReader
from xlutils.filter import process, XLRDReader, XLWTWriter
Quickstart
import xlrd
import xlwt
from xlutils.copy import copy
# Create a dummy .xls file first for demonstration
wb_initial = xlwt.Workbook()
ws_initial = wb_initial.add_sheet('Sheet1')
ws_initial.write(0, 0, 'Hello')
ws_initial.write(0, 1, 'World')
ws_initial.write(1, 0, 'Original Value')
wb_initial.save('example_input.xls')
# Open the existing workbook with xlrd
rb = xlrd.open_workbook('example_input.xls', formatting_info=True)
# Make a writable copy of the workbook using xlutils.copy
wb = copy(rb)
# Get the first sheet from the copied workbook
ws = wb.get_sheet(0)
# Write a new value to a cell (e.g., cell B2)
ws.write(1, 1, 'Modified Value')
# Save the modified workbook to a new .xls file
wb.save('example_output.xls')
print("Modified workbook saved as 'example_output.xls'")
# Clean up dummy file (optional)
import os
os.remove('example_input.xls')
os.remove('example_output.xls')