Cannot write output excel file with openpyxl

763 views Asked by At

I have been working on a script using openpyxl that has been working properly up until yesterday when I accidentally closed my GUI mid-process. Since that time my script has been unable to save to a new excel file in any directory. I am using PyCharm as my IDE. Whenever I run the script I receive the following error:

WindowsError: [Error 32] The process cannot access the file because it is being used by another process: 'c:\users\username\appdata\local\temp\openpyxl.izzaxe'

This was working properly so I do not believe it is an issue with my code, but I have included a snippet below:

wb = load_workbook(filename=r'PATH TO SOME EXCEL FILE')
header = wb['Sheet1'][1:1]
listheader = []
for h in listheader:
    listheader.append(h.value)
wb['Sheet2'].append(listheader)
wb.save(filename=r'PATH TO A DIFFERENT EXCEL FILE'

I have closed PyCharm and re-opened but still receive the error message. I have also navigated to **c:\users\username\appdata\local\temp** and deleted the file causing the block, but when I re-run my script a new openpyxl file with a different extension becomes generated in the same directory and blocks my script from saving the new file. I currently have 5 different openpyxl temp files with random extensions in my **appdata\local\temp** directory

I have also restarted my computer and uninstalled and reinstalled openpyxl with pip both with no success. I have also attempted to run the script through CMD and with IDLE, but I receive the same error message.

I am using Python 2.7 which is required as it is the default python installation that comes with ArcGIS and I need access to the arcpy module's metadata functionality which has no Python 3 equivalent. Any help is greatly appreciated.

1

There are 1 answers

0
MapPeddler On

It turns out this was actually being caused by a portion of my code. I was defining column dimensions for my output as follows:

wb['Sheet1'].column_dimensions['A'] = 100
wb['Sheet1'].column_dimensions['C'] = 50
wb['Sheet1'].column_dimensions['D'] = 50
wb['Sheet1'].column_dimensions['E'] = 150
wb['Sheet1'].column_dimensions['F'] = 150

Not including the width attribute was what was causing the script to fail. Revising the above to the following fixed my problem:

wb['Sheet1'].column_dimensions['A'].width = 100
wb['Sheet1'].column_dimensions['C'].width = 50
wb['Sheet1'].column_dimensions['D'].width = 50
wb['Sheet1'].column_dimensions['E'].width = 150
wb['Sheet1'].column_dimensions['F'].width = 150

This may be a duplicate of the following thread where I found my answer: Stuck on AttributeError: 'int' object has no attribute 'reindex' when trying to save workbook in openpyxl