Search code examples
pythonpython-3.xxlrdxlsxwriterxlwt

Python: Open Excel Workbook If it Exists or Create it


I am trying to get a good method to see if an Excel spreadsheet exists, if it does use that, if not create a new excel file. See code snippet below. The weird thing is every time I run it, it crashed on first attempt. If I run it again, it cruises through. Any ideas why? I am thinking it has something to do with xlrd vs. xlwt, but haven't found a solution yet. All modules are up-to-date.

import pandas as pd
import xlsxwriter
from xlrd import open_workbook
import xlwt
import os.path

fname=r'testmonthlyz.xlsm'
fname2=r'testmonthlyoutput2.xlsx'
#workbook = xlsxwriter.Workbook(fname2)    
if os.path.isfile(fname2):
    print('old file')
    book=open_workbook(fname2)
else:
    print('new file')
    book=xlwt.Workbook(fname2)
    ws = book.add_sheet('Tested')
sheet_names=book.sheet_names()

Solution

  • I believe that the reason that is crashed is since when you are in the else section, you have the line book=xlwt.Workbook(fname2) which means the book type is Workbook which has no attribute called sheet_names().
    When you are using book = open_workbook(fname2) inside the if, book type is Book which does have sheet_names() attribute.
    my solution to this, even though is's not the best way, but I think it will solve the issue you are dealing with.. change the following lines

    import pandas as pd
    import xlsxwriter
    from xlrd import open_workbook
    import xlwt
    import os.path
    
    fname=r'testmonthlyz.xlsm'
    fname2=r'testmonthlyoutput2.xlsx'
    workbook = xlsxwriter.Workbook(fname2)    
    if os.path.isfile(fname2):
        print('old file')
        book=open_workbook(fname2)
    else:
        print('new file')
        workbook2=xlwt.Workbook(fname2)
        ws = workbook2.add_sheet('Tested')
        workbook2.save(fname2)
        book = open_workbook(fname2)
    
    sheet_names=book.sheet_names()