Reputation: 3
I want to verify if the excel sheet has already exist in the current workbook.
Here is the Code:
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)
Upvotes: 0
Views: 2349
Reputation: 10392
I looked at the docs for xlwt and there seems to only an add_sheet
with no way of detecting duplicates or fetching existing sheets. On the other hand, xlsxwriter docs seems to have a better add_worksheet method as it raises an exception on a duplicate (which you could catch and handle).
So, something like this:
try:
worksheet = workbook.add_worksheet(sheetName)
except xlsxwriter.exceptions.DuplicateWorksheetName:
worksheet = workbook.get_worksheet_by_name(sheetName)
It's always helpful to read through the docs for the libraries you're using for answers.
Upvotes: 1