mat
mat

Reputation: 2617

openpyxl: assign value or apply format to a range of Excel cells without iteration

I would like to apply a specific format or assign a value to a range of Excel cells without iterating over each cell. I am currently using this script:

from openpyxl import Workbook
from openpyxl.styles import Font
wb = Workbook()
ws = wb.active

## With iterations

# Apply style
for i, rowOfCellObjects in enumerate(ws['A1':'C4']):
    for n, cellObj in enumerate(rowOfCellObjects):
        cellObj.fill = Font(name='Times New Roman')

# Assign singular value to all cells
for i, rowOfCellObjects in enumerate(ws['A1':'C4']):
    for n, cellObj in enumerate(rowOfCellObjects):
        cellObj.value = 3

wb.save("test.xlsx")

But I am looking for a shorter notation, like this:

from openpyxl import Workbook
from openpyxl.styles import Font
wb = Workbook()
ws = wb.active

## Without iterations

# Apply style
ws['A1':'C4'].fill = Font(name='Times New Roman')

# Assign singular value to all cells
ws['A1':'C4'].value = 3

wb.save("test.xlsx")

Does openpyxl or another module offers something like this?

ps: I'm using Python 3.5

Upvotes: 15

Views: 25822

Answers (2)

Gleb Erofeev
Gleb Erofeev

Reputation: 196

This is not quite exact. OpenPyxel allows to apply styles to columns and rows:

According to: https://openpyxl.readthedocs.io/en/stable/styles.html

Styles can also applied to columns and rows but note that this applies only to cells created (in Excel) after the file is closed. If you want to apply styles to entire rows and columns then you must apply the style to each cell yourself. This is a restriction of the file format:

col = ws.column_dimensions['A']
col.font = Font(bold=True)
row = ws.row_dimensions[1]
row.font = Font(underline="single")

Upvotes: 18

Charlie Clark
Charlie Clark

Reputation: 19507

In Excel styles must be applied to individual cells because this is how the file format works. Because of the way it works, openpyxl does not provide the desired functionality, but it is possible with xlsxwriter.

Upvotes: 12

Related Questions