user12810571
user12810571

Reputation:

Openpyxl worksheet does not exist

I'm attempting to write to a cell using openpyxl, but am getting error "Worksheet Sheet1 does not exist."

def CreateWorkbook(workbook_path):
    workbook = openpyxl.Workbook()
    workbook.save(workbook_path)
    return workbook_path

def CreateSheet(workbook, sheet_name):
    workbook.create_sheet(sheet_name)
    workbook.save(workbook_path)
    return sheet_name

def WriteCell(workbook, sheet_name, cell, cell_data):
    worksheet = workbook[sheet_name]
    worksheet[cell] = cell_data
    return

workbook = CreateWorkbook('workbook1.xlsx')
sheet = CreateSheet(workbook, 'Sheet1')
WriteCell(workbook, sheet, 'A1', 'testing')

Upvotes: 0

Views: 2865

Answers (2)

The Pilot Dude
The Pilot Dude

Reputation: 2237

This code isn't really good and has multiple errors. For example, in CreateWorkbook, you create a workbook, and then save it. However, after, in CreateSheet, you don't actually, reopen the file. The file must be re opened after every save. This is how I would fix those errors:

import openpyxl

def CreateWorkbook(workbook_path):    
    workbook = openpyxl.Workbook()
    workbook.save(workbook_path)
    return workbook_path

def CreateSheet(workbook, sheet_name):
    wb = openpyxl.load_workbook(workbook)
    wb.create_sheet(sheet_name)
    wb.save(workbook)
    return sheet_name

def WriteCell(workbook, sheet_name, cell, cell_data):
    wb = openpyxl.load_workbook(workbook)
    worksheet = wb[sheet_name]
    worksheet[cell] = cell_data
    wb.save(workbook)
    return

workbook = CreateWorkbook('workbook1.xlsx')
sheet = CreateSheet(workbook, 'Sheet1')
WriteCell(workbook, sheet, 'A1', 'testing')

Upvotes: 2

Petronella
Petronella

Reputation: 2535

Maybe you should post the complete class code, there are some things that don't really make sense like for instance in:

def CreateSheet(workbook, sheet_name):
workbook.create_sheet(sheet_name)
workbook.save(workbook_path)
return sheet_name

when you return sheet_name - this is basically the same value as you give in the input, it's pointless. Secondly, you use workbook_path as a parameter, I assume it's a class attribute, otherwise it's not clear how you have it in the method.

Also in:

def CreateWorkbook(workbook_path):
workbook = openpyxl.Workbook()
workbook.save(workbook_path)
return workbook_path

you return the same input argument workbook_path which again dosn't make sense and in the code below you use the workbook_path as workbook. This here might be the error, but there are a few so might be also sth else.

For your problem try to debug the code, eventually print out at every method a "proof" that the object created was actually created.

Upvotes: 0

Related Questions