杰瑞科技汇

Python xlwt中xfstyle如何设置单元格样式?

Of course! Let's dive deep into xlwt's XFStyle object. It's the cornerstone of making your Excel files with xlwt look professional and readable.

Python xlwt中xfstyle如何设置单元格样式?-图1
(图片来源网络,侵删)

What is XFStyle?

In xlwt, XF stands for eXtended Format. An XFStyle object is a container that holds all the formatting properties for a cell or a range of cells. Think of it as a "style template" that you can apply to any number of cells.

Instead of formatting each cell individually (e.g., setting its font, borders, and alignment one by one), you create an XFStyle object with all the desired properties once, and then simply apply that style to the cells when you write to them. This is much more efficient and keeps your code clean.


How to Use XFStyle: A Step-by-Step Guide

Here’s the typical workflow:

  1. Import xlwt: import xlwt
  2. Create a Workbook: workbook = xlwt.Workbook()
  3. Add a Worksheet: worksheet = workbook.add_sheet('Sheet1')
  4. Create an XFStyle Object: style = xlwt.XFStyle()
  5. Configure Properties of the style Object: Set the font, borders, alignment, etc.
  6. Apply the Style to a Cell: worksheet.write(row, col, 'Your Data', style=style)

Key Properties of an XFStyle Object

An XFStyle object has several key attributes that you can set. Here are the most common ones with examples.

Python xlwt中xfstyle如何设置单元格样式?-图2
(图片来源网络,侵删)

Font (font)

Controls the appearance of the text.

  • name: Font name (e.g., 'Arial', 'Times New Roman')
  • height: Font height in 1/20th of a point. (e.g., 200 for 10pt, 240 for 12pt)
  • bold: True or False
  • italic: True or False
  • colour: Font color. This is an index from a color palette.
  • underline: Style of underline ('single', 'double', 'none')

Example: Creating a Bold, Italic, Red Font

import xlwt
# Create a style object
header_style = xlwt.XFStyle()
# Configure the font
font = xlwt.Font()
font.name = 'Arial'
font.bold = True
font.italic = True
# Note: xlwt uses a color index, not a hex code.
# 0x0F is a standard red. You can find a color chart online.
font.colour_index = 0x0F 
# Assign the font to the style
header_style.font = font

Borders (borders)

Controls the cell's border lines.

  • left, right, top, bottom: Border style for each side.
  • colour: Border color.

Border Styles:

Python xlwt中xfstyle如何设置单元格样式?-图3
(图片来源网络,侵删)
  • xlwt.Borders.THIN
  • xlwt.Borders.MEDIUM
  • xlwt.Borders.THICK
  • xlwt.Borders.NO_LINE

Example: Adding Thin, Black Borders

# Create another style object
border_style = xlwt.XFStyle()
# Configure the borders
borders = xlwt.Borders()
borders.left = xlwt.Borders.THIN
borders.right = xlwt.Borders.THIN
borders.top = xlwt.Borders.THIN
borders.bottom = xlwt.Borders.THIN
# 0x00 is black
borders.left_colour = 0x00
borders.right_colour = 0x00
borders.top_colour = 0x00
borders.bottom_colour = 0x00
# Assign the borders to the style
border_style.borders = borders

Alignment (alignment)

Controls the horizontal and vertical positioning of text within a cell.

  • horiz: Horizontal alignment.
    • xlwt.Alignment.HORZ_GENERAL (default)
    • xlwt.Alignment.HORZ_LEFT
    • xlwt.Alignment.HORZ_CENTER
    • xlwt.Alignment.HORZ_RIGHT
    • xlwt.Alignment.HORZ_JUSTIFY
  • vert: Vertical alignment.
    • xlwt.Alignment.VERT_TOP
    • xlwt.Alignment.VERT_CENTER
    • xlwt.Alignment.VERT_BOTTOM
  • wrap: True or False for text wrapping.

Example: Centering Text and Wrapping

# Create a centered style
centered_style = xlwt.XFStyle()
# Configure the alignment
alignment = xlwt.Alignment()
alignment.horz = xlwt.Alignment.HORZ_CENTER
alignment.vert = xlwt.Alignment.VERT_CENTER
alignment.wrap = True # Wrap text if it's too long
# Assign the alignment to the style
centered_style.alignment = alignment

Pattern (pattern)

Controls the cell's background color.

  • pattern: The fill pattern type.
    • xlwt.Pattern.SOLID_PATTERN (for a solid color fill)
  • fore_colour: The foreground color of the pattern. This is the color you'll see.

Example: Yellow Background

# Create a highlighted style
highlight_style = xlwt.XFStyle()
# Configure the pattern
pattern = xlwt.Pattern()
pattern.pattern = xlwt.Pattern.SOLID_PATTERN
# 0x17 is a standard yellow in the xlwt palette
pattern.fore_colour = 0x17
# Assign the pattern to the style
highlight_style.pattern = pattern

Putting It All Together: A Complete Example

Let's create a simple report with headers, data, and totals, each with its own style.

import xlwt
from datetime import datetime
# 1. Create a workbook and add a sheet
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('Sales_Report')
# --- Define Styles ---
# Style for headers (Bold, Italic, Red text, Yellow background)
header_style = xlwt.XFStyle()
header_font = xlwt.Font()
header_font.name = 'Arial'
header_font.bold = True
header_font.italic = True
header_font.colour_index = 0x0F  # Red
header_pattern = xlwt.Pattern()
header_pattern.pattern = xlwt.Pattern.SOLID_PATTERN
header_pattern.fore_colour = 0x17  # Yellow
header_style.font = header_font
header_style.pattern = header_pattern
# Style for data (Thin borders, general alignment)
data_style = xlwt.XFStyle()
data_borders = xlwt.Borders()
data_borders.left = xlwt.Borders.THIN
data_borders.right = xlwt.Borders.THIN
data_borders.top = xlwt.Borders.THIN
data_borders.bottom = xlwt.Borders.THIN
data_borders.left_colour = 0x00
data_borders.right_colour = 0x00
data_borders.top_colour = 0x00
data_borders.bottom_colour = 0x00
data_style.borders = data_borders
# Style for totals (Bold, Right-aligned, Blue text)
total_style = xlwt.XFStyle()
total_font = xlwt.Font()
total_font.name = 'Arial'
total_font.bold = True
total_font.colour_index = 0x0C  # Blue
total_alignment = xlwt.Alignment()
total_alignment.horz = xlwt.Alignment.HORZ_RIGHT
total_style.font = total_font
total_style.alignment = total_alignment
# --- Write Data to the Sheet ---
# Headers
worksheet.write(0, 0, 'Product', header_style)
worksheet.write(0, 1, 'Quantity', header_style)
worksheet.write(0, 2, 'Price', header_style)
worksheet.write(0, 3, 'Total', header_style)
# Data
data = [
    ['Laptop', 10, 1200.50],
    ['Mouse', 50, 25.00],
    ['Keyboard', 30, 75.75],
    ['Monitor', 15, 300.00]
]
row = 1
for product, qty, price in data:
    worksheet.write(row, 0, product, data_style)
    worksheet.write(row, 1, qty, data_style)
    worksheet.write(row, 2, price, data_style)
    worksheet.write(row, 3, qty * price, data_style)
    row += 1
# Total row
worksheet.write(row, 2, 'Grand Total:', total_style)
worksheet.write(row, 3, sum(item[1] * item[2] for item in data), total_style)
# --- Save the file ---
filename = f'sales_report_{datetime.now().strftime("%Y%m%d_%H%M%S")}.xls'
workbook.save(filename)
print(f"Excel file '{filename}' created successfully!")

Important Limitation: xlwt vs. openpyxl

It's crucial to know that xlwt has a major limitation: it can only create .xls files, not the modern .xlsx format.

For any new project, especially if you need to work with large files or the .xlsx format, openpyxl is the recommended library.

Here's how the same concept of styling works in openpyxl for comparison:

# openpyxl example (for reference)
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
wb = Workbook()
ws = wb.active
# In openpyxl, you apply styles directly to cell objects
# Header style
header_font = Font(bold=True, color="FF0000") # Hex color
header_fill = PatternFill(start_color="FFFF00", end_color="FFFF00", fill_type="solid")
header_alignment = Alignment(horizontal="center", vertical="center")
# Apply to cells
for cell in ws[1]:
    cell.font = header_font
    cell.fill = header_fill
    cell.alignment = header_alignment
# ... and so on for other styles
wb.save("openpyxl_report.xlsx")

As you can see, openpyxl uses a more object-oriented approach where you create style objects (like Font, PatternFill) and assign them directly to the .font, .fill, etc., attributes of a cell object. This is often considered more intuitive.

分享:
扫描分享到社交APP
上一篇
下一篇