Skip to content
Advertisement

Copying the segment from one Excel file to another with python: xlrd and xlsxwriter

I am trying to copy an entire segment of an Excel sheet to another file. The segment is actually a header/description, which mainly describes the attributes of the file, the date it was created, etc… All this takes some cells at first five rows and first 3 columns, say from A1:C3. Here’s the code I’ve written (for sake of example, made only for 3 rows):

JavaScript

The counters, data, list values – everything seems to be correct and on time, according to print commands, however, when I run this code, in the newly created file only 3’rd row gets populated, rows 1 and 2 are EMPTY. Don’t understand why… To test the issue, made another example-a really inelegant one – no looping, control lists, etc-just blunt approach:

JavaScript

In THIS case everything worked out fine and all the needed data was transferred. Anyone can explain me what is wrong with the first one? Thank you.

Additional trouble I have is if I, after placing header, start to populate columns, the header values become NULL. That is despite me, starting column population from the cell below the “header” cell(in the code, I provide below it’s column 1, starting from cell 6. Any ideas on how to solve it?

JavaScript

UPDATE: Here’s the revised code, after Mike’s correction:

JavaScript

After running this I get the following error “Traceback (most recent call last): File “C:/Users/Michael/PycharmProjects/untitled/cleaner.py”, line 28, in worksheet.write_row(row_header_list[i], data) IndexError: list index out of range Exception Exception: Exception(‘Exception caught in workbook destructor. Explicit close() may be required for workbook.’,) in > ignored”. The “line 28” refers to:

JavaScript

running the entire segment from the beginning to finalizing the loop seems to be fine and provide correct output, thus the problem is down below. If I use the explicit close method, as suggested, I will not be able to use add_sheet method again, since it’ll run over my current sheet. In the provided documentation there are “sheet.activate” and “sheet.select” methods, but they seem to be for cosmetic improvement reasons. I have tried to place the xlsxwriter’s work into a different variable (although if I place all the “copying” process at the top, I don’t ming “workbook” being run over) – didn’t help

Advertisement

Answer

You create new output file with the same name in each loop:

JavaScript

Therefore, you overwrite the file in each loop and only the last row gets saved.

Just move this out of the loop:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement