1

I am trying to open and format a specific Excel worksheet. However I am having trouble trying to find out how to look at a specific worksheet.

The code I'm trying to use to open the workbook and go to a specific worksheet and then change the font for specific cells is:

from openpyxl import Workbook

def applyValidations(path,tabname):
 workbook = Workbook(path)
 worksheet = workbook[tabname]
 c = worksheet['A1:A5']
 c.font = Font(size=22)

The error I'm getting is:

KeyError: 'Worksheet Department Data does not exist.'

Department Data is the name of the worksheet which does exist in the workbook.

halfer
  • 19,824
  • 17
  • 99
  • 186
Stacey
  • 4,825
  • 17
  • 58
  • 99
  • Are you passing `Department Data ` as a string? If so, it may be case sensitivity that produces the error. See this answer for a possible solution : https://stackoverflow.com/a/55807617/2570277 – Nick Jul 08 '19 at 09:54
  • Use `workbook.sheetnames` to get a list of all the worksheets in the workbook and check carefully for whitespace. – Charlie Clark Jul 08 '19 at 11:24
  • 2
    Looking at the code, it looks like you should be using `load_workbook()` and not `Workbook()` to open an existing file. – Charlie Clark Jul 08 '19 at 15:50
  • if so @CharlieClark, my solution should be correct. No? – Yaakov Bressler Jul 08 '19 at 19:48
  • 1
    @YaakovBressler no, not least because you've chosen read-only mode and the question is about **modifying** a workbook. But also your answer does not identify or explain the problem. Hence, it is a poor answer. – Charlie Clark Jul 09 '19 at 07:56

1 Answers1

-1

Here's some code I use regularly with openpyxl, which may solve your Q:

from openpyxl import load_workbook
wb = load_workbook(filename=data_file, read_only=True)

ws = wb.active
print(wb.sheetnames)
Yaakov Bressler
  • 9,056
  • 2
  • 45
  • 69