Whole column background formatted the same manner with openpyxl doesn't work as intended

Question:

MRE:

import openpyxl
from openpyxl.styles import PatternFill

# Create a new workbook
workbook = openpyxl.Workbook()

# Select the active sheet
sheet = workbook.active

# Set the background color of the third column to black
fill = PatternFill(start_color='000000', end_color='000000', fill_type='solid')
for cell in sheet['C']:
    cell.fill = fill

# Save the workbook
workbook.save('example.xlsx')

Only the first cell of column ‘C’ is with black background.

I want the whole column to be formatted with black background (like it works in Excel when you format the whole column).

I don’t want to iterate through cells from 1 to a big number because otherwise the Excel file created is created with loads of rows. It should be that the format is applied to the whole column without creating new rows, like it works in Excel basically. Is that possible? Or do I need to run xlwings to call a VBA function?

Answers:

Certainly Xlwings can do it, without a VBA function.
Just do

import xlwings as xw


wb = xw.Book()
ws = wb.sheets[0]

ws.range('C:C').color = (0,0,0)

Answered By: moken
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.