I want to set the same background color and the cell border color for the whole worksheet.
I could not find a solution anywhere that applies to the whole sheet.
I want to set the same background color and the cell border color for the whole worksheet.
I could not find a solution anywhere that applies to the whole sheet.
As @Gino Mempin states, Openpyxl works with cells so you would need to set the background for all cells in the sheet. You may then prefer to then just change a range of cells rather than the whole sheet.
It may be best to use iter_rows for memory use.
The example fills 1000 rows and columns. The max size of a sheet may be up to 1,048,576 rows by 16,384 columns doing the whole sheet may take some time. I don't know if Openpyxl provides the total limits as a value to use in the code its unusual to need them, so you may need to enter as fixed values. As mentioned you may only want to change a range like the 'used range' covered by
ws.max_row
ws.max_column
This example changes the cell color to red...
from openpyxl import load_workbook
from openpyxl.styles import PatternFill
filename = 'foo.xlsx'
wb = load_workbook(filename)
ws = wb['Sheet1']
for row in ws.iter_rows(max_row=1000, max_col=1000):
for cell in row:
print(cell)
cell.fill = PatternFill("solid", fgColor="FF0000")
wb.save(filename)
You can edit the default background and borders of the whole worksheet by editing the default values of the workbook, but I don't know how legit it is:
import openpyxl
from openpyxl import Workbook
from openpyxl.styles import PatternFill
from openpyxl.styles.borders import Border, Side
wb = Workbook()
# Add a patternfill solid white (this hide the usual grid around a cell)
j = wb._fills.add(PatternFill("solid",start_color="FFFFFFFF"))
# Add a thick border to all sides style
k = wb._borders.add(Border(left=Side(style='thick'),
right=Side(style='thick'),
top=Side(style='thick'),
bottom=Side(style='thick')))
# Update the default style with the new values
wb._cell_styles[0] = openpyxl.styles.cell_style.StyleArray([0, j, k, 0, 0, 0, 0, 0, 0])