如何在 Python 中使用 Aspose.Cells FOSS 对单元格进行样式设置

如何在 Python 中使用 Aspose.Cells FOSS 对单元格进行样式设置

Aspose.Cells FOSS for Python 让您能够对单个单元格使用字体样式和背景填充,使用 the cell.style.fontcell.style.fill API。颜色表示为 8-digit AARRGGBB hex strings;;例如 "FFFF0000" 表示不透明的红色,且没有 # 前缀。所有样式均在纯 Python 中完成,不依赖 Microsoft Excel 或任何外部渲染库。.

为什么要使用 Aspose.Cells FOSS 对单元格进行样式设置??

  1. 无需 Excel::格式化完全在任何操作系统上的 Python 中运行。.
  2. 一致的颜色模型::单个 8 位的 AARRGGBB 字符串即可覆盖字体颜色和填充颜色,采用相同的格式。.
  3. 可读属性名称: bold, italic, underline, strikethrough: 否 is_ 用于记忆的前缀。.
  4. 可重用的字体对象: 创建一个 Font 实例一次,并将其应用于多个单元格,以保持品牌一致性。.

分步指南

步骤 1:为 Python 安装 Aspose.Cells FOSS

pip install aspose-cells-foss

不需要额外的系统软件包。请从 aspose.cells_foss:

from aspose.cells_foss import Workbook, Cell, Font, SaveFormat

步骤 2:设置字体名称和大小

通过 ws.cells["address"] 并写入 cell.style.font.namecell.style.font.size.

from aspose.cells_foss import Workbook

workbook = Workbook()
ws = workbook.worksheets[0]

ws.cells["A1"].value = "Styled Header"

cell = ws.cells["A1"]
cell.style.font.name = "Arial"
cell.style.font.size = 14

workbook.save("styled.xlsx")

默认字体是 Calibri,11pt.。任何在打开文件的系统上可用的字体名称都可以使用;指定未安装的字体不会导致错误,但在打开文件时可能会使用回退字体进行渲染。.


步骤 3:使用 AARRGGBB 十六进制字符串设置字体颜色

字体颜色使用一种 8-digit hexadecimal stringAARRGGBB 顺序(Alpha、Red、Green、Blue)。请 不要 包含 # 前缀。.

from aspose.cells_foss import Workbook

workbook = Workbook()
ws = workbook.worksheets[0]

ws.cells["A1"].value = "Red text"
ws.cells["A1"].style.font.color = "FFFF0000"   # opaque red

ws.cells["A2"].value = "Blue text"
ws.cells["A2"].style.font.color = "FF0000FF"   # opaque blue

ws.cells["A3"].value = "Green text"
ws.cells["A3"].style.font.color = "FF00FF00"   # opaque green

workbook.save("colored_text.xlsx")

常用 AARRGGBB 颜色参考::

颜色AARRGGBB 字符串备注
黑色FF000000默认字体颜色
白色FFFFFFFF用于深色背景
红色FFFF0000警报或突出显示文本
蓝色FF0000FF链接或强调
绿色FF00FF00正值或成功
橙色FFFF8000警告文本
灰色FF808080柔和或禁用的文本
海军蓝FF1E64C8企业/品牌蓝

前两个十六进制数字是 alpha 通道。使用 FF 表示完全不透明。低于此值的 FF 在支持 alpha 混合的渲染器中生成半透明的结果。.


步骤 4:应用粗体、斜体、下划线和删除线

将每个属性直接设置为布尔值。属性名称为 bold, italic, underline,,以及 strikethrough;;执行 不要 使用 is_boldis_italic (这些名称在 FOSS API 中不存在,并且会导致 AttributeError).

from aspose.cells_foss import Workbook

workbook = Workbook()
ws = workbook.worksheets[0]

ws.cells["A1"].value = "Bold"
ws.cells["A1"].style.font.bold = True

ws.cells["A2"].value = "Italic"
ws.cells["A2"].style.font.italic = True

ws.cells["A3"].value = "Underline"
ws.cells["A3"].style.font.underline = True

ws.cells["A4"].value = "Strikethrough"
ws.cells["A4"].style.font.strikethrough = True

ws.cells["A5"].value = "Bold + Italic"
ws.cells["A5"].style.font.bold = True
ws.cells["A5"].style.font.italic = True

workbook.save("font_styles.xlsx")

所有四个标志默认 False.。它们可以在同一单元格中自由组合。.


步骤 5:设置纯色背景填充

使用 cell.style.fill.set_solid_fill("AARRGGBB") 以应用背景填充。颜色格式与字体颜色相同,使用相同的 8 位 AARRGGBB 十六进制字符串。.

要完全移除填充,请调用 cell.style.fill.set_no_fill().

from aspose.cells_foss import Workbook

workbook = Workbook()
ws = workbook.worksheets[0]

ws.cells["A1"].value = "Navy background"
ws.cells["A1"].style.fill.set_solid_fill("FF1E64C8")   # opaque navy blue

ws.cells["A2"].value = "Light yellow background"
ws.cells["A2"].style.fill.set_solid_fill("FFFFFFCC")   # pale yellow

ws.cells["A3"].value = "No fill"
ws.cells["A3"].style.fill.set_no_fill()                 # remove any fill

workbook.save("cell_fills.xlsx")

set_solid_fill()set_no_fill() 是互斥的;在同一单元格上调用其中一个会覆盖另一个。.


步骤 6:在单个单元格上组合多种样式

可以在同一单元格引用上链式设置任意数量的样式属性。设置的样式属性数量在保存之前没有限制。.

from aspose.cells_foss import Workbook

workbook = Workbook()
ws = workbook.worksheets[0]

ws.cells["B2"].value = "Branded Header"

cell = ws.cells["B2"]

##Font
cell.style.font.name  = "Arial"
cell.style.font.size  = 16
cell.style.font.bold  = True
cell.style.font.color = "FFFFFFFF"      # white text

##Background
cell.style.fill.set_solid_fill("FF1E64C8")   # navy fill

workbook.save("branded_header.xlsx")
print("Branded header cell saved.")

这会在海军蓝背景上生成一个白色、粗体、16pt Arial 的标签,这是列标题的常见模式。.


步骤 7:使用 Font 构造函数创建可复用的样式

Font 类可以在一次调用中实例化并设置所有属性,然后分配给多个单元格。当您希望在许多单元格中应用一致的内部样式,而无需重复相同的属性赋值时,这非常有用。.

from aspose.cells_foss import Workbook, Font

workbook = Workbook()
ws = workbook.worksheets[0]

##Define a reusable heading font
heading_font = Font(
    name="Arial",
    size=14,
    color="FF1E64C8",   # navy
    bold=True,
    italic=False,
    underline=False,
    strikethrough=False
)

##Define a reusable body font
body_font = Font(
    name="Calibri",
    size=11,
    color="FF000000",   # black (default)
    bold=False,
    italic=False,
    underline=False,
    strikethrough=False
)

##Apply heading font to header row
headers = ["Product", "SKU", "Price", "Stock"]
for col, header in enumerate(headers):
    addr = f"{chr(65 + col)}1"
    ws.cells[addr].value = header
    ws.cells[addr].style.font = heading_font
    ws.cells[addr].style.fill.set_solid_fill("FFE8EFF9")  # light blue tint

##Apply body font to data rows
data = [
    ("Widget A", "WGT-001", 9.99,  150),
    ("Widget B", "WGT-002", 14.99, 87),
    ("Widget C", "WGT-003", 4.49,  320),
]

for row_idx, (name, sku, price, stock) in enumerate(data, start=2):
    ws.cells[f"A{row_idx}"].value = name
    ws.cells[f"B{row_idx}"].value = sku
    ws.cells[f"C{row_idx}"].value = price
    ws.cells[f"D{row_idx}"].value = stock
    for col in "ABCD":
        ws.cells[f"{col}{row_idx}"].style.font = body_font

workbook.save("product_table.xlsx")
print("Product table with reusable fonts saved.")

Font 构造函数默认值 (所有参数均为可选)::

参数默认
name"Calibri"
size11
color"FF000000"
boldFalse
italicFalse
underlineFalse
strikethroughFalse

完整可运行示例

下面的独立脚本会创建一个工作簿,其中包含带样式的标题行、彩色数据行以及展示上述所有样式 API 的汇总单元格::

from aspose.cells_foss import Workbook, Cell, Font, SaveFormat

workbook = Workbook()
ws = workbook.worksheets[0]
ws.name = "Sales Report"

##--- Header row (bold, white text on navy background) ---
headers = ["Region", "Q1", "Q2", "Q3", "Q4", "Total"]
for col, text in enumerate(headers):
    addr = f"{chr(65 + col)}1"
    ws.cells[addr].value = text
    ws.cells[addr].style.font.name  = "Arial"
    ws.cells[addr].style.font.size  = 12
    ws.cells[addr].style.font.bold  = True
    ws.cells[addr].style.font.color = "FFFFFFFF"            # white
    ws.cells[addr].style.fill.set_solid_fill("FF1E64C8")    # navy

##--- Data rows ---
data = [
    ("North", 42000, 47500, 53000, 61000),
    ("South", 31000, 28500, 35000, 39000),
    ("East",  55000, 62000, 58000, 71000),
    ("West",  27000, 30000, 33000, 41000),
]

for row_idx, (region, q1, q2, q3, q4) in enumerate(data, start=2):
    ws.cells[f"A{row_idx}"].value = region
    ws.cells[f"B{row_idx}"].value = q1
    ws.cells[f"C{row_idx}"].value = q2
    ws.cells[f"D{row_idx}"].value = q3
    ws.cells[f"E{row_idx}"].value = q4
    # Total formula
    ws.cells[f"F{row_idx}"] = Cell(None, f"=SUM(B{row_idx}:E{row_idx})")
    # Alternate row shading
    if row_idx % 2 == 0:
        for col in "ABCDEF":
            ws.cells[f"{col}{row_idx}"].style.fill.set_solid_fill("FFE8EFF9")

##--- Italic note in a footer cell ---
ws.cells["A7"].value = "All values in USD"
ws.cells["A7"].style.font.italic = True
ws.cells["A7"].style.font.color  = "FF808080"   # gray
ws.cells["A7"].style.font.size   = 9

##--- Strikethrough on a deprecated label ---
ws.cells["A8"].value = "Old metric (deprecated)"
ws.cells["A8"].style.font.strikethrough = True
ws.cells["A8"].style.font.color         = "FF808080"

workbook.save("sales_report_styled.xlsx", SaveFormat.XLSX)
print("Styled sales report saved.")

常见问题

错误的颜色格式:使用 #RRGGBB 而不是 AARRGGBB

前导 # (例如. "#FF0000") 或 6 位 RGB 字符串将无法产生预期的颜色。该属性恰好需要 8 hex digits with no prefix: "FFFF0000".。前两个数字是 alpha 通道;使用 FF 表示完全不透明。.

AttributeError: 'Font' object has no attribute 'is_bold'

FOSS API 使用 bold, italic, underline,,并且 strikethrough 作为属性名称。该 is_bold / is_italic 命名约定属于另一个库,在此不存在。请替换所有 is_bold 引用为 bold.

保存后样式更改未显示

确保在单元格对象上设置样式属性 调用 workbook.save(). 在保存调用之后对单元格设置属性不会影响已写入的文件。如果重新使用一个 cell 变量,请确认它仍然指向正确的单元格地址。.

同一单元格的填充和字体在视觉上冲突

不存在 API 冲突;您始终可以同时设置两者 cell.style.font.colorcell.style.fill.set_solid_fill() 独立。确保文字颜色与背景颜色之间有足够的对比度。白色文字(FFFFFFFF)在深色填充(如海军蓝(FF1E64C8)是可靠的组合。.


常见问题

如何移除背景填充并将单元格恢复为无填充??

调用 cell.style.fill.set_no_fill().。这将移除单元格中先前设置的任何实心填充。.

如何将单元格重置为默认字体(Calibri 11pt 黑色)??

显式重新分配默认值::

cell.style.font.name          = "Calibri"
cell.style.font.size          = 11
cell.style.font.color         = "FF000000"
cell.style.font.bold          = False
cell.style.font.italic        = False
cell.style.font.underline     = False
cell.style.font.strikethrough = False

或者,创建一个 Font() 不带参数的实例(全部默认),并将其分配:: cell.style.font = Font().

我可以在循环中将相同的字体样式应用于一系列单元格吗??

是的。遍历单元格地址并对每个单元格设置相同的属性。如果使用 Font 构造函数来创建共享的 Font 对象,将其分配给每个单元格,使用 ws.cells[addr].style.font = my_font.

样式会影响单元格的值或公式吗??

不。样式纯粹是视觉元数据。. cell.style.fontcell.style.fill 不要触碰 .value.formula.

哪些保存格式会保留样式??

保存为时,样式会被完整保留 SaveFormat.XLSX.。该 SaveFormat.CSV, SaveFormat.TSV, SaveFormat.JSON,,以及 SaveFormat.MARKDOWN 格式是纯文本或结构化文本格式,不包含样式信息。.


相关资源::

 中文