Python XLWT attempt to overwrite cell workaround

前端 未结 4 589
悲&欢浪女
悲&欢浪女 2020-12-09 05:01

Using the python module xlwt, writing to the same cell twice throws an error:

Message File Name   Line    Position    
Traceback               
    

        
相关标签:
4条回答
  • 2020-12-09 05:08

    The problem is that overwriting of worksheet data is disabled by default in xlwt. You have to allow it explicitly, like so:

    worksheet = workbook.add_sheet("Sheet 1", cell_overwrite_ok=True)
    
    0 讨论(0)
  • 2020-12-09 05:15

    You should get in touch with the author of the module. Simply removing a raise is unlikely to work well. I would guess that it would lead to other problems further down the line. For example, later code may assume that any given cell is only in the intermediate representation once.

    0 讨论(0)
  • 2020-12-09 05:19

    If you:

    • don't want to set the entire worksheet to be able to be overwritten in the constructor, and
    • still catch the exception on a case-by-case basis

    ...try this:

    try:
        worksheet.write(row, col, "text")
    except:
        worksheet._cell_overwrite_ok = True
        # do any required operations since we found a duplicate
        worksheet.write(row, col, "new text")
        worksheet._cell_overwrite_ok = False
    
    0 讨论(0)
  • 2020-12-09 05:24

    What Ned B. has written is valuable advice -- except for the fact that as xlwt is a fork of pyExcelerator, "author of the module" is ill-defined ;-)

    ... and Kaloyan Todorov has hit the nail on the head.

    Here's some more advice:

    (1) Notice the following line in the code that you quoted:

    if not self.__parent._cell_overwrite_ok:
    

    and search the code for _cell_overwrite_ok and you should come to Kaloyan's conclusion.

    (2) Ask questions on (and search the archives of) the python-excel google-group

    (3) Check out this site which gives pointers to the google-group and to a tutorial.

    Background: the problem was that some people didn't know what they were doing (and in at least one case were glad to be told), and the behaviour that xlwt inherited from pyExcelerator was to blindly write two (or more) records for the same cell, which led not only to file bloat but also confusion, because Excel would complain and show the first written and OpenOffice and Gnumeric would silently show the last written. Removing all trace of the old data from the shared string table so that it wouldn't waste space or (worse) be visible in the file was a PITA.

    The whole saga is recorded in the google-group. The tutorial includes a section on overwriting cells.

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