如果 python 中不存在,如何使用 xlwings 添加新的 sheet

How to add new sheet if it's not exist in python using xlwings

在 python 中使用 xlwings,我想在现有工作簿中添加新的 sheet。如果 sheet 已经存在于相同的名称中,它应该 return sheet 数据帧。

import xlwings as xw

wb = xw.Book('file_path')
try:
    wb.sheets.add('sheetname')
except ValueError as V:
    print("Error:", V)

我使用以下辅助函数添加 sheet(如果它尚不存在)或 get/activate(如果它已经存在):

def addActivate(wb, sheetName, template=None):
    try:
        sht = wb.sheets(sheetName).activate()
    except com_error:
        if template:
            template.sheets["Template"].api.Copy(wb.sheets.active.api)
            sht = wb.sheets["Template"].api.Name = sheetName
        else:
            sht = wb.sheets.add(sheetName)
    return sht

在任何情况下,都会返回 sheet。该函数还允许定义 sheet 名称的名称,用作新 sheet.

的模板