如何在Python 2.7中使用xlsxwriter或xlwt修改单元格格式?
Hey there! This is such a common pitfall when moving from CSV to Excel with XlsxWriter—let’s walk through exactly how to fix this.
First, let’s clarify the key point about XlsxWriter: it’s a write-only library. That means once you’ve written data to a cell, you can’t go back and change the cell’s format without overwriting the data. So your hunch is right—you absolutely need to handle formatting and data type conversion before writing to the Excel file.
Here’s the step-by-step solution:
1. Convert CSV String Values to Numeric Types First
The root issue is that your CSV stores all values as strings, so when you write them directly to Excel, XlsxWriter treats them as text. The fix is to convert numeric-looking strings to actual Python int or float values before writing.
Here’s a concrete code example using the built-in csv module:
import csv import xlsxwriter # Initialize your Excel workbook and worksheet workbook = xlsxwriter.Workbook('converted_data.xlsx') worksheet = workbook.add_worksheet() # Read your CSV file and process each cell with open('input_data.csv', 'r') as csv_file: csv_reader = csv.reader(csv_file) row_idx = 0 for row in csv_reader: col_idx = 0 for cell_value in row: # Try to convert the string to a number try: # Check for decimals to decide int vs float if '.' in cell_value: processed_value = float(cell_value) else: processed_value = int(cell_value) except ValueError: # If conversion fails, keep it as a string processed_value = cell_value # Write the processed value—XlsxWriter will handle the cell type automatically worksheet.write(row_idx, col_idx, processed_value) col_idx += 1 row_idx += 1 workbook.close()
When you write a Python numeric type (int/float) to Excel with XlsxWriter, it automatically creates a numeric cell (not text) without extra formatting work.
2. Add Custom Numeric Formatting (If Needed)
If you want to apply specific formatting to your numeric cells (like currency, decimal places, or percentages), create a format object first and pass it to the write method:
# Create a custom format (e.g., 2 decimal places) numeric_format = workbook.add_format({'num_format': '0.00'}) # When writing a numeric value, include the format worksheet.write(row_idx, col_idx, processed_value, numeric_format)
This way, your cell is both a numeric type and formatted exactly how you want it—all in one write operation.
Quick Note on Edge Cases
If your CSV has numeric values with extra characters (like $1,234.56 or 1,000), you’ll need to clean those strings before conversion:
# Example: Remove commas and dollar signs cleaned_value = cell_value.replace('$', '').replace(',', '') processed_value = float(cleaned_value)
To wrap it up: Yes, pre-processing your data and setting formats before writing is the only way to avoid losing data with XlsxWriter. By converting strings to actual numbers first, you’ll get properly typed Excel cells that support calculations right away.
内容的提问来源于stack exchange,提问作者Jeremy_L




