Unable to style range of cells

Issue #414 on hold
Josh Haywood created an issue

Styling a range of cells doesn't seem to be supported. The following code returns an AttributeError: 'generator' object has no attribute 'style'.

import tkinter as tk
from tkinter import filedialog
import csv, random
from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl.styles import Style, PatternFill, Border, Side, Alignment, Protection, Font, Color       

###Some Code Here###

def onRandoClick(self):

        count = 0
        data = []
        header = ["Animal #", "Weight (g)"]

        while count < self.totalAnimals.get():
            data.append(self.startAnimalNum.get() + count)
            count += 1

        random.shuffle(data)

        wb = Workbook()
        ws = wb.active
        ws.cell('A1').value = header[0]
        ws.cell('B1').value = header[1]
        j = 0
        for i in range(2, self.totalAnimals.get() + 1):
            ws.cell(row = i, column = 1).value = data[j]
            j = j + 1

        endRow = str(self.totalAnimals.get() + 1)
        sel = ws['A2':'B%s' % endRow]
        sel.style = Style(font=Font(color=Color('ff0000')))

        wb.save(self.randoFilepath + '//%s Randomization.xlsx' % self.studyNumber.get())

        root.destroy()

###Some Code Here###

Comments (5)

  1. CharlieC

    Yes, you cannot style ranges and you never will be able to like that because a range always returns a list or a generator. You will have to loop through the range returned and apply a style to each cell in it. Open for suggestions (with code) as to how it might look otherwise.

  2. Josh Haywood reporter

    Fair enough. I'm not familiar enough with the project to have a code suggestion yet, but maybe a note in the docs would clarify that only cells, rows, and columns can be styled? If I come up with a code suggestion in the future I'll bring it back in.

  3. Log in to comment