Edit existing excel workbooks and sheets with xlrd and xlwt

后端 未结 2 1724
梦谈多话
梦谈多话 2020-11-29 01:44

In the documentation for xlrd and xlwt I have learned the following:

How to read from existing work-books/sheets:

from xlrd         


        
相关标签:
2条回答
  • 2020-11-29 02:07

    Here's another way of doing the code above using the openpyxl module that's compatible with xlsx. From what I've seen so far, it also keeps formatting.

    from openpyxl import load_workbook
    wb = load_workbook('names.xlsx')
    ws = wb['SheetName']
    ws['A1'] = 'A1'
    wb.save('names.xlsx')
    
    0 讨论(0)
  • 2020-11-29 02:22

    As I wrote in the edits of the op, to edit existing excel documents you must use the xlutils module (Thanks Oliver)

    Here is the proper way to do it:

    #xlrd, xlutils and xlwt modules need to be installed.  
    #Can be done via pip install <module>
    from xlrd import open_workbook
    from xlutils.copy import copy
    
    rb = open_workbook("names.xls")
    wb = copy(rb)
    
    s = wb.get_sheet(0)
    s.write(0,0,'A1')
    wb.save('names.xls')
    

    This replaces the contents of the cell located at a1 in the first sheet of "names.xls" with the text "a1", and then saves the document.

    0 讨论(0)
提交回复
热议问题