Search code examples
python-2.7xlrdxlsxwriter

How to create/Delete sheet without changing old sheets for .xls files?


I have tried to create new sheet using xlsxwriter.add_worksheet() but Its changing my old sheets.Any library which can create a new sheet without effecting other sheets and How can i delete sheet in .xls file because I didn't find any function in xlrd or xlsxwriter which can delete a sheet.

Edit:1 Tried using win32 module. Able to delete the sheet but unable to create new sheet without effecting existing sheets.


Solution

  • Update: Found the answer

    Creating a new sheet :

    import xlrd
    xl_ref = xlrd.open_workbook('Path to file')
    

    Here type(xl_ref) is <class 'xlrd.book.Book> So when we call function

    xl_ref.add_sheet('Test1')
    

    There got the error book object has no attribute.So basically whenever we want to manipulate .xls file without affecting existing changes.first, convert into workbook object.

    from xlutils.copy import copy
    xlwb_ref=copy(xl_ref)
    xlwb_ref.add_sheet('Test1')
    xlwb_ref.save('Path to file')
    

    Reference: Python_doc

    Deleting Sheet :

        import pythoncom
        from win32com.client.gencache import EnsureDispatch
        pythoncom.CoInitialize() #if Calling same thing again and again so better reinitialize. 
        excel = EnsureDispatch("Excel.Application")
        excel_file = excel.Workbooks.Open("Path to file")
        sheet = excel.Sheets("Sheet name")
        sheet.Delete()
        excel_file.Close(True)