Search code examples
excelpython-2.7excel-2013xlsxwriter

update excel files in python 2.7


I need to edit an excel file but without overwriting the old content I'm using xlsxwriter to create the excel file but it does not have this option is there any solution ?


Solution

  • xlsxwriter module documentation states:

    Module cannot read or modify existing Excel XLSX files.

    There are other python modules that allow you modify existing .xlsx files. Since you mentioned that you had created an existing workbook using xlsxwriter, I've put an example below that creates a file using xlsxwriter then reopens, modifies and saves the same file using the openpyxl module (link to openpyxl documentation).

    import xlsxwriter
    import openpyxl
    from openpyxl import Workbook, worksheet, load_workbook`
    
    workbook = xlsxwriter.Workbook("test.xlsx")
    worksheet = workbook.add_worksheet('Sheet')
    worksheet.write('A1', 'This cell was written using xlsxwriter')
    workbook.close()`
    
    wb = openpyxl.load_workbook("test.xlsx")
    ws = wb.active
    ws['A2'] = 'This cell was written using openpyxl'`
    
    wb.save("test.xlsx")