workbook: Workbook = Workbook(“配方模板.xlsx”)
cell_sheet: Worksheet = workbook.worksheets[0]
获取当前工作范围
cells_range: Range = cell_sheet.cells.create_range(
first_row=cell_sheet.cells.min_data_row,
first_column=cell_sheet.cells.min_data_column,
total_rows=(
cell_sheet.cells.max_data_row -
cell_sheet.cells.min_data_row + 1
),
total_columns=(
cell_sheet.cells.max_data_column -
cell_sheet.cells.min_data_column + 1
)
)
创建一个新的 Style 对象
style: Style = workbook.create_style()
style: Style = Style()
设置 Style 的背景色为 None(清除背景色)
style.background_color = Color.red
style_flag = StyleFlag()
style_flag.all = True
将样式应用到指定范围
cells_range.set_style(style, explicit_flag=True)
cells_range.apply_style(style, style_flag)
print(cells_range)
workbook.save(‘Hello.xlsx’) 为什么背景色设置无效
代码是这个
读取工作簿
workbook: Workbook = Workbook(“配方模板.xlsx”)
cell_sheet: Worksheet = workbook.worksheets[0]
获取当前工作范围
cells_range: Range = cell_sheet.cells.create_range(
first_row=cell_sheet.cells.min_data_row,
first_column=cell_sheet.cells.min_data_column,
total_rows=(
cell_sheet.cells.max_data_row -
cell_sheet.cells.min_data_row + 1
),
total_columns=(
cell_sheet.cells.max_data_column -
cell_sheet.cells.min_data_column + 1
)
)
创建一个新的 Style 对象
style: Style = Style()
style.background_color = Color.red
将样式应用到指定范围
cells_range.set_style(style, explicit_flag=True)
print(cells_range)
workbook.save(‘Hello.xlsx’)
@zengweiyu
请参考以下样例代码:
from aspose.cells import Workbook, ImportTableOptions, Style, StyleFlag, BackgroundType
from aspose.pydrawing import Color
workbook = Workbook("配方模板.xlsx")
cell_sheet = workbook.worksheets[0]
#获取当前工作范围
cells_range = cell_sheet.cells.create_range(
first_row=cell_sheet.cells.min_data_row,
first_column=cell_sheet.cells.min_data_column,
total_rows=(
cell_sheet.cells.max_data_row -
cell_sheet.cells.min_data_row + 1
),
total_columns=(
cell_sheet.cells.max_data_column -
cell_sheet.cells.min_data_column + 1
)
)
#创建一个新的 Style 对象
style = workbook.create_style()
style.foreground_color = Color.red
style.pattern = BackgroundType.SOLID
flag = StyleFlag()
flag.all = True
#将样式应用到指定范围
cells_range.apply_style(style, flag)
print(cells_range)
workbook.save("Hello.xlsx")
关于如何格式化范围,你也可以参考以下文档:
1 Like
@zengweiyu
如果你设置一个solid pattern 的颜色,请设置style.pattern and style.foreground_color
style = workbook.create_style()
style.pattern = BackgroundType.SOLID
style.foreground_color = Color.red