Search code examples
pythonexcelopenpyxlxlwt

How to write a data into an exist sheet of excel file by Python?


I'm looking for a way to write some data into an excel file. Then I found xlwt seems can reach my requirement, but I only find the way to add a new sheet. for example:

sheet = workbook.add_sheet('test222')

If I hope to enter a value into an exist sheet "test 111", does someone know how to do that?

My sample code:

import xlwt

def write_report():
    f_value = "500"
    workbook = xlwt.Workbook('D:\\Test.xls')
    sheet = workbook.add_sheet('test222')
    sheet.write(5, 3, f_value)

    workbook.save('D:\\Test.xls')

Thanks a lot.





[Update on 7/31/2018]
After I used the method of import openpyxl, I met a weird issue. Some borders were disappeared after I write data into the file.
Original: enter image description here

After I wrote data into the file: enter image description here

The border of some fields which have been merged were cleared. (item A, item B, Category 01 and Category 02) Is it the known issue on openpyxl?


Solution

  • This is minmal example:

    import openpyxl
    
    wbkName = 'New.xlsx'
    wbk = openpyxl.load_workbook(wbkName)
    wks = wbk['test1']
    someValue = 1337
    wks.cell(row=10, column=1).value = someValue
    wbk.save(wbkName)
    wbk.close
    

    The saving with the explicit name of the workbook seems to be quite important - wbk.save(wbkName), because only wbk.save does not do the job completely, but does not throw an error.