import xlwings as xw
from xlwings.utils import rgb_to_int, int_to_rgb
filename = "foo.xlsx"
red = (255, 0, 0)
with xw.App() as app:
wb = xw.Book(filename)
ws = wb.sheets('Sheet1')
### Any one of the following will set the whole sheet to a red background
ws.api.Cells.Interior.ColorIndex = 3
# ws.api.Cells.Interior.Color = rgb_to_int(red)
# ws.api.Cells.Interior.Color = '&H0000FF'
### Cell Border color can also be set with Color or ColorIndex same as background color
### Also the weight and style with the following
ws['A1'].api.Borders.ColorIndex = 3
# ws['A1'].api.Borders.Color = '&H0000FF' # or use rgb_to_int(red)
ws['A1'].api.Borders.Weight = 3
ws['A1'].api.Borders.LineStyle = 1
wb.save(filename)
wb.close()
1条答案
按热度按时间njthzxwz1#
正如@Gino Mempin所述,Openpyxl使用单元格,因此您需要为工作表中的所有单元格设置背景。然后,您可能更喜欢只更改单元格范围,而不是整个工作表。
但是,如果您必须设置整个工作表,您可以使用Xlwing来实现这一点(Xlwing需要在本地安装Excel,因此需要安装Windows(或MACOS))。
xlwings