杰瑞科技汇

Python xlwt 如何设置单元格对齐方式?

Of course! Here’s a comprehensive guide on how to align text in an Excel file using the xlwt library in Python.

xlwt is a popular library for creating spreadsheet files compatible with older versions of Microsoft Excel (.xls format). The key to alignment is using the Alignment class.

Summary of Key Classes

  • xlwt.Alignment: This is the class you use to define alignment properties.
  • xlwt.XFStyle: This is the "eXtended Format" style object. You don't apply alignment directly to a cell. Instead, you create an XFStyle object, set its alignment property, and then apply that style to the cell.

Basic Horizontal Alignment

Horizontal alignment is the most common type. You can align text to the general (default), left, center, or right.

Available Horizontal Alignment Constants:

  • xlwt.Alignment.HORZ_GENERAL (Default)
  • xlwt.Alignment.HORZ_LEFT
  • xlwt.Alignment.HORZ_CENTER
  • xlwt.Alignment.HORZ_RIGHT
  • xlwt.Alignment.HORZ_JUSTIFY (Stretches text to fill the cell width)

Example: Centering Text in a Cell

import xlwt
# 1. Create a new workbook and select a sheet
workbook = xlwt.Workbook()
sheet = workbook.add_sheet("Sheet1")
# 2. Create a style for center alignment
center_style = xlwt.XFStyle()
# Create an Alignment object
alignment = xlwt.Alignment()
# Set the horizontal alignment to center
alignment.horz = xlwt.Alignment.HORZ_CENTER
# Apply the alignment to the style
center_style.alignment = alignment
# 3. Write to the cell using the style
sheet.write(0, 0, "This text is centered", center_style)
# 4. Save the workbook
workbook.save("horizontal_alignment.xls")
print("File 'horizontal_alignment.xls' created successfully.")

Example: Right-Aligning Text

import xlwt
workbook = xlwt.Workbook()
sheet = workbook.add_sheet("Sheet1")
# Create a style for right alignment
right_style = xlwt.XFStyle()
right_style.alignment = xlwt.Alignment(horz=xlwt.Alignment.HORZ_RIGHT)
# Write to the cell
sheet.write(1, 0, "This text is right-aligned", right_style)
workbook.save("horizontal_alignment.xls")

Vertical Alignment

You can also control how text is positioned vertically within a cell's row height.

Available Vertical Alignment Constants:

  • xlwt.Alignment.VERT_TOP
  • xlwt.Alignment.VERT_CENTER
  • xlwt.Alignment.VERT_BOTTOM (Default)
  • xlwt.Alignment.VERT_JUSTIFY (Stretches text to fill the cell height)

Example: Centering Text Vertically

import xlwt
workbook = xlwt.Workbook()
sheet = workbook.add_sheet("Sheet1")
# To see the effect, let's make the row taller
sheet.row(0).height_mismatch = True
sheet.row(0).height = 500 # 1/20 of a point, so 500 is a tall row
# Create a style for vertical centering
vertical_center_style = xlwt.XFStyle()
vertical_center_style.alignment = xlwt.Alignment(vert=xlwt.Alignment.VERT_CENTER)
# Write to the cell
sheet.write(0, 0, "Vertically Centered", vertical_center_style)
workbook.save("vertical_alignment.xls")
print("File 'vertical_alignment.xls' created successfully.")

Combining Horizontal and Vertical Alignment

This is where XFStyle becomes powerful. You can combine multiple alignment properties into a single style.

Example: Centering Text Both Horizontally and Vertically

import xlwt
workbook = xlwt.Workbook()
sheet = workbook.add_sheet("Sheet1")
# Make the cell larger to see the effect
sheet.row(0).height_mismatch = True
sheet.row(0).height = 500
sheet.col(0).width = 5000 # Set a wider column
# Create a style for both horizontal and vertical centering
center_all_style = xlwt.XFStyle()
# You can pass arguments directly to the Alignment constructor
center_all_style.alignment = xlwt.Alignment(
    horz=xlwt.Alignment.HORZ_CENTER,
    vert=xlwt.Alignment.VERT_CENTER
)
# Write to the cell
sheet.write(0, 0, "Centered All Ways", center_all_style)
workbook.save("combined_alignment.xls")
print("File 'combined_alignment.xls' created successfully.")

Other Useful Alignment Properties

xlwt.Alignment also has other properties for more advanced formatting.

wrap

This property controls whether text should wrap onto multiple lines if it exceeds the column width.

  • Value: True or False (boolean)
  • Constant: xlwt.Alignment.WRAP_NONE (False) or xlwt.Alignment.WRAP_AT_RIGHT (True)

Example: Text Wrapping

import xlwt
workbook = xlwt.Workbook()
sheet = workbook.add_sheet("Sheet1")
# Set a wider column to see the wrapping effect
sheet.col(0).width = 5000
# Create a style for wrapping text
wrap_style = xlwt.XFStyle()
wrap_style.alignment = xlwt.Alignment(wrap=True)
# Write long text to the cell
sheet.write(0, 0, "This is a long piece of text that should wrap onto the next line within the cell boundaries.", wrap_style)
workbook.save("text_wrap.xls")
print("File 'text_wrap.xls' created successfully.")

rotation

This property allows you to rotate the text in the cell. The value is in degrees, from -90 to 90.

  • Value: An integer representing degrees.
  • Note: xlwt's rotation can be a bit quirky. Positive values rotate counter-clockwise, and negative values rotate clockwise.

Example: Rotated Text

import xlwt
workbook = xlwt.Workbook()
sheet = workbook.add_sheet("Sheet1")
# Create a style for rotated text
rotate_style = xlwt.XFStyle()
rotate_style.alignment = xlwt.Alignment(rotation=45) # Rotate 45 degrees counter-clockwise
sheet.write(0, 0, "Rotated Text", rotate_style)
workbook.save("rotated_text.xls")
print("File 'rotated_text.xls' created successfully.")

Complete Example: All Alignment Types in One File

Here is a script that creates a single Excel file demonstrating all the concepts discussed.

import xlwt
# --- Setup ---
workbook = xlwt.Workbook()
sheet = workbook.add_sheet("Alignment Demo")
# Set column widths for better visibility
sheet.col(0).width = 3000
sheet.col(1).width = 5000
sheet.col(2).width = 5000
# Make row 0 taller for vertical alignment demo
sheet.row(0).height_mismatch = True
sheet.row(0).height = 600
sheet.row(1).height_mismatch = True
sheet.row(1).height = 600
# --- Style Definitions ---
# 1. Left-aligned
left_style = xlwt.XFStyle()
left_style.alignment = xlwt.Alignment(horz=xlwt.Alignment.HORZ_LEFT)
# 2. Center-aligned (horizontal)
center_h_style = xlwt.XFStyle()
center_h_style.alignment = xlwt.Alignment(horz=xlwt.Alignment.HORZ_CENTER)
# 3. Right-aligned
right_style = xlwt.XFStyle()
right_style.alignment = xlwt.Alignment(horz=xlwt.Alignment.HORZ_RIGHT)
# 4. Vertically centered
center_v_style = xlwt.XFStyle()
center_v_style.alignment = xlwt.Alignment(vert=xlwt.Alignment.VERT_CENTER)
# 5. Centered both ways
center_all_style = xlwt.XFStyle()
center_all_style.alignment = xlwt.Alignment(
    horz=xlwt.Alignment.HORZ_CENTER,
    vert=xlwt.Alignment.VERT_CENTER
)
# 6. Wrapped text
wrap_style = xlwt.XFStyle()
wrap_style.alignment = xlwt.Alignment(wrap=True)
# --- Writing Data to the Sheet ---
sheet.write(0, 0, "Horizontal Alignment:")
sheet.write(1, 0, "Left", left_style)
sheet.write(1, 1, "Center", center_h_style)
sheet.write(1, 2, "Right", right_style)
sheet.write(3, 0, "Vertical Alignment:")
sheet.write(4, 0, "Top", xlwt.XFStyle(alignment=xlwt.Alignment(vert=xlwt.Alignment.VERT_TOP)))
sheet.write(4, 1, "Center", center_v_style)
sheet.write(4, 2, "Bottom", xlwt.XFStyle(alignment=xlwt.Alignment(vert=xlwt.Alignment.VERT_BOTTOM)))
sheet.write(6, 0, "Combined & Special:")
sheet.write(7, 0, "Centered All Ways", center_all_style)
sheet.write(8, 0, "This text is wrapped and will fit inside the column width.", wrap_style)
# --- Save the Workbook ---
workbook.save("alignment_summary.xls")
print("File 'alignment_summary.xls' created successfully.")

This will generate a file named alignment_summary.xls that you can open to see all the different alignment styles in action.

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