Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
627 views
in Technique[技术] by (71.8m points)

python - 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')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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')

I hope this works for you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...