欢迎访问宙启技术站
智能推送

get_style_by_name()函数的用法示例及效果展示

发布时间:2023-12-24 15:48:09

get_style_by_name()函数是一个可以根据给定的名称获取相应样式的函数。下面是一个使用示例:

from openpyxl.styles import Font, Alignment, Border, Side
from openpyxl import Workbook


def get_style_by_name(style_name):
    if style_name == "title":
        return Font(name="Arial", bold=True, size=14)
    elif style_name == "header":
        return Font(name="Arial", bold=True, size=12)
    elif style_name == "body":
        return Font(name="Calibri", size=11), Alignment(horizontal="center"), Border(left=Side(border_style="thin"), right=Side(border_style="thin"), top=Side(border_style="thin"), bottom=Side(border_style="thin"))


# 创建一个新的Workbook对象
workbook = Workbook()
sheet = workbook.active

# 设置标题样式
title_style = get_style_by_name("title")
title_cell = sheet.cell(row=1, column=1)
title_cell.value = "Sales Report"
title_cell.font = title_style

# 设置表头样式
header_style = get_style_by_name("header")
header_row = sheet.row_dimensions[2]
header_row.height = 30
header_cells = ["Date", "Product", "Quantity", "Price", "Total"]
for i, cell_value in enumerate(header_cells):
    header_cell = sheet.cell(row=2, column=i+1)
    header_cell.value = cell_value
    header_cell.font = header_style

# 设置正文样式
body_style = get_style_by_name("body")
data = [
    ["2022-01-01", "Product A", 10, 15.99, "=C3*D3"],
    ["2022-01-02", "Product B", 5, 12.99, "=C4*D4"],
    ["2022-01-03", "Product C", 8, 19.99, "=C5*D5"],
    ["2022-01-04", "Product D", 3, 9.99, "=C6*D6"],
]
for row_num, row_data in enumerate(data, start=3):
    for col_num, cell_value in enumerate(row_data, start=1):
        cell = sheet.cell(row=row_num, column=col_num)
        cell.value = cell_value

        if isinstance(body_style, Font):
            cell.font = body_style
        elif isinstance(body_style, Alignment):
            cell.alignment = body_style
        elif isinstance(body_style, Border):
            cell.border = body_style

# 保存文件
workbook.save("sales_report.xlsx")

在上面的示例中,我们首先定义了一个get_style_by_name(style_name)函数来根据给定的样式名称返回相应的样式对象。

接下来,我们创建了一个新的Workbook对象,并获取了默认的活动工作表对象。

然后,我们使用get_style_by_name()函数来获取不同的样式,并将每个单元格的样式设置为相应的样式。我们首先设置了标题单元格的样式,然后设置了表头单元格的样式,最后设置了正文单元格的样式。

在正文单元格的样式设置中,我们使用了多个样式对象(Font, Alignment, Border)来设置单元格的字体,对齐方式和边框。

最后,我们保存了Workbook对象到一个名为"sales_report.xlsx"的Excel文件中。

运行上述代码后,将会生成一个包含有标题、表头和正文数据的销售报表的Excel文件。