Python XLWT attempt to overwrite cell workaround

PPTim picture PPTim · Apr 21, 2010 · Viewed 34.8k times · Source

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

Message File Name   Line    Position    
Traceback               
    <module>    S:\******** 
    write   C:\Python26\lib\site-packages\xlwt\Worksheet.py 1003        
    write   C:\Python26\lib\site-packages\xlwt\Row.py   231     
    insert_cell C:\Python26\lib\site-packages\xlwt\Row.py   150     
Exception: Attempt to overwrite cell: sheetname=u'Sheet 1' rowx=1 colx=12   

with the code snippet

def insert_cell(self, col_index, cell_obj):
        if col_index in self.__cells:
            if not self.__parent._cell_overwrite_ok:
                msg = "Attempt to overwrite cell: sheetname=%r rowx=%d colx=%d" \
                    % (self.__parent.name, self.__idx, col_index)
                raise Exception(msg) #row 150
            prev_cell_obj = self.__cells[col_index]
            sst_idx = getattr(prev_cell_obj, 'sst_idx', None)
            if sst_idx is not None:
                self.__parent_wb.del_str(sst_idx)
        self.__cells[col_index] = cell_obj

Looks like the code 'raise'es an exception which halts the entire process. Is removing the 'raise' term enough to allow for overwriting cells? I appreciate xlwt's warning, but i thought the pythonic way is to assume "we know what we're doing". I don't want to break anything else in touching the module.

Answer

ktdrv picture ktdrv · Apr 21, 2010

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)