openpyxl load_workbook遇guess_types参数错误,单元格格式异常
Hey there! Let's tackle your two openpyxl problems one by one—first that annoying TypeError, then keeping your cell formats intact when appending data.
1. Fixing the TypeError: unexpected keyword argument 'guess_types'
The guess_types parameter was removed in newer versions of openpyxl (it was deprecated way back in v2.4 and dropped entirely later). This parameter used to help the library guess cell data types, but openpyxl's type-handling logic has been updated to work without it.
Instead of using guess_types=True, adjust your load_workbook call based on what you need:
- If you want to read cell values (not formulas), use
data_only=True:wb = load_workbook(filename=self.file_name, data_only=True) - If you don't need to skip formulas, just omit the parameter entirely:
wb = load_workbook(filename=self.file_name)
2. Preserving Cell Formats When Appending Data
By default, ws.append() adds new cells with the 'General' format because openpyxl doesn't automatically inherit formatting from existing rows. To keep your original cell types/formats, you'll need to manually copy styles from a reference row (like the last row of your existing data) to the new row you append.
Here's a practical example:
from openpyxl import load_workbook from openpyxl.styles import copy_style # Load the workbook (without guess_types!) wb = load_workbook(filename=self.file_name) ws = wb.active # Get the last row with existing data to use as a style reference last_existing_row = ws.max_row reference_cells = ws[last_existing_row] if last_existing_row >= 1 else None # Your new data to append new_row_data = ["Alice Smith", 28, "Designer"] # Append the raw data first ws.append(new_row_data) # Get the newly added row new_row = ws[ws.max_row] # Copy styles from the reference row to the new row if reference_cells: for new_cell, ref_cell in zip(new_row, reference_cells): copy_style(ref_cell, new_cell) # Save the updated workbook wb.save(self.file_name)
Notes:
- If specific columns have fixed formats (e.g., dates, currency), you can also define reusable styles with
openpyxl.styles.NamedStyleand apply them directly to new cells instead of copying from a reference row. - Make sure you're running the latest version of openpyxl—double-check with
pip install --upgrade openpyxlif you haven't already.
内容的提问来源于stack exchange,提问作者Daniel Surizon

