我如何验证工作表中已经存在Excel工作表?

时间:2019-01-23 16:06:12

标签: excel python-3.x

我想验证当前工作簿中是否已经存在Excel工作表。

以下是代码:

import xlwt
from xlwt import Workbook
import xlsxwriter

lst = ['Task', 'Status', 'Created_Date', 'Moved_Date']
value = []

wb = Workbook()

def write_excel(fileName, sheetName, *args):
    ws = wb.add_sheet(sheetName)

    style0 = xlwt.easyxf('font: bold on')
    for col, value in enumerate(lst):
        ws.write(0, col, value, style0)
        ws.col(col).width = 0x0d00 + col
        # for row, value in enumerate():

    wb.save(fileName)

write_excel('sample_xl.xls', 'sheet1', lst)

1 个答案:

答案 0 :(得分:0)

我看着docs for xlwt,似乎只有add_sheet无法检测重复或获取现有的纸张。另一方面,xlsxwriter docs seems to have a better add_worksheet method会在重复项上引发异常(您可以捕获并处理)。

所以,像这样:

try:
    worksheet = workbook.add_worksheet(sheetName)
except xlsxwriter.exceptions.DuplicateWorksheetName:
    worksheet = workbook.get_worksheet_by_name(sheetName)

通读文档以获取用于答案的库。