openpyxl corrupt output after save - delete and rename worksheet

Viewed 61

I have 30 .xlsx input files.

I would like to do the below

a) Read each input file

b) delete few sheets in them

c) Rename few sheets in them

d) Save and close the file

So, I tried the below and am using version 3.0.9 of openpyxl. I also tried using 3.0.10, 3.0.3 versions of openpyxl

%%time
files = glob.glob('FY2022_*.xlsx')
for old_filename in files:
    print(old_filename)
    input_file = openpyxl.load_workbook(old_filename)
    del input_file['5b)Development']
    del input_file['only_Structure']
    del input_file['9)Definition_']
    input_sheet = input_file['5a)Development']
    input_sheet.title = '5)Development'
    input_file.save(old_filename)
    input_file.close()

While the code works without any error, but I realized that some of the saved files are corrupted. I referred this post and verified that my view is normal. I don't have custom view setup. But I can say that my input excel files are strictly formatted (with lot of formatting rules, colors, merge etc). But the same formatting is applied across all 30 workbooks. So, am not sure why it works for few files and not for other files.

Out of 30 input files, am able to open only 15-17 files. Rest of the files throw a message like below

We found a problem with some content in FY2022_ABC.xlsx. Do you want us to try to recover as much as we can? If you trust the source, click Yes

And when I click yes, for all these error workbooks, format is lost etc. and all these error workbooks open at a different worksheet (ex: sheet no 2) whereas error-free workbooks open at work sheet no 1)

How can I avoid this and make it work by just deleting sheets and renaming them?

0 Answers
Related