I am trying to save an excel file generated by another application that is open. i.e the excel application is in the foreground. This file has some data and it needs to be saved i.e written into the disk.
In other words, I need to do an operation like File->SaveAs.
Steps to reproduce:
Open an Excel Application. This will be shown as Book1 - Excel in the title by default
Write this code and run
import win32com.client as win32
app = win32.gencache.EnsureDispatch('Excel.Application')
app.Workbooks(1).SaveAs(r"C:\Users\test\Desktop\test.xlsx")
app.Application.Quit()
Error -
Traceback (most recent call last):
File "c:/Users/test/Downloads/automate_excel.py", line 6, in <module>
ti = disp._oleobj_.GetTypeInfo()
pywintypes.com_error: (-2147418111, 'Call was rejected by callee.', None, None)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:/Users/test/Downloads/automate_excel.py", line 6, in <module>
app = win32.gencache.EnsureDispatch('Excel.Application')
File "C:\Users\test\AppData\Local\Programs\Python\Python38\lib\site-packages\win32com\client\gencache.py", line 633, in EnsureDispatch
raise TypeError(
TypeError: This COM object can not automate the makepy process - please run makepy manually for this object
There could be many sources for your problem so I would apreciate if you shared further code. The second error can for example occur when you are running multiple instances of the line excel = win32.gencache.EnsureDispatch('Excel.Application') for example in a for loop .
Also make sure to have a version of excel that is fully activated and licensed .
This is working for me (on python==3.9.8 and pywin32==305). You'll see that the first line is a different than yours, but I think that's really it.
In the course of this we kept getting Attribute Errors for the Workbook or for setting DisplayAlerts. We found (from this question: Excel.Application.Workbooks attribute error when converting excel to pdf) that if Excel is in a loop (for example, editing a cell or has a pop-up open) then you will get an error. So, be sure to click enter out of a cell so that you aren't editing it.
import win32com.client as win32
savepath = 'c:\\my\\file\\path\\test\\'
xl = win32.Dispatch('Excel.Application')
wb = xl.Workbooks['Book1']
wb.DisplayAlerts = False # helpful if saving multiple times to save file, it means you won't get a pop-up for overwrite and will default to save it.
filename = 'new_xl.xlsx'
wb.SaveAs(savepath+filename)
wb.Close()
xl.Quit()
edit: add pywin32 version, include some more tips
This is the version that worked for me based on #scotscotmcc's answer. The issue was with the cell which was in edit mode while I was running the program. Make sure you hit enter in the current cell and come out of the edit mode in excel.
import win32com.client as win32
import random
xl = win32.Dispatch('Excel.Application')
wb = xl.Workbooks['Book1']
wb.SaveAs(r"C:\Users\...\Desktop\Form"+str(random.randint(0,1000))+".xlsx")
wb.Close()
xl.Quit()
Related
import openpyxl
input_workbook1 = openpyxl.load_workbook('/dbfs/FileStore/Test/my_excel.xlsx')
sheet_1 = input_workbook1.active
sheet_1['A2'] = 'A2'
input_workbook1.save('/dbfs/FileStore/Test/Output.xlsx')
OSError: [Errno 95] Operation not supported
I tried reading the excel file directly using openpyxl in databricks , I can able to read and modify directly without pandas/dataframes, but when I am trying to save i.e last line in above code facing the issue.I tried exactly the same way but facing the above error , can anyone help me please
I tried doing the same procedure and it gave me the same error OSError: [Errno 95] Operation not supported. The reason for this is that there is a limitation that random writes do not work on the local file system and here is the official Microsoft documentation (Local File API limitations) which refers to this issue.
So, try instead of trying to write to the local file system, write the file to /databricks/driver/ path and then copy/move the file to required directory.
Modify your code as following:
import openpyxl
input_workbook1 = openpyxl.load_workbook('/dbfs/FileStore/Test/my_excel.xlsx')
sheet_1 = input_workbook1.active
sheet_1['A2'] = 'A2'
input_workbook1.save('Output.xlsx')
#will be saved to '/databricks/driver/'.
#Use dbutils.fs.ls('/databricks/driver/') to view.
from shutil import move
move('/databricks/driver/Output.xlsx','/dbfs/FileStore/Test/')
wb1 = openpyxl.load_workbook('/dbfs/FileStore/Output.xlsx')
ws1 = wb1.active
for row in ws1.iter_rows():
print([col.value for col in row])
The above code will successfully move your file to the required path without any errors.
I am trying to run vba macro from Python but the excel file which has macro is already open. So I want to not open it again as another instance.
I have tried win32com code - however it reopens another instance of the same file and makes changes in that instance and ask me to save as second excel file. But i want to call macro in already open file. and after calling that macro leave the excel file open.
this is the path where File is located - its a private shared drive
\nplofnp0001a\gtonnnfs10912400\CPM Other\PL Estimate\PL Estimate Sheets\DAILY PL ESTIMATE W NRPD RV2 v6_YK_v2.xlsm
folder_xlfile = '\\\\nplofnp0001a\gtonnnfs10912400\CPM Other\PL Estimate\PL Estimate Sheets'
xlfile = '\\DAILY PL ESTIMATE W NRPD RV2 v6_YK_v2.xlsm'
Filename=folder_xlfile + xlfile
import win32com.client
xl=win32com.client.DispatchEx("Excel.Application")
#wb = xl.Workbooks.Open(Filename)
xl.Application.Run(Filename + "!Module2.CopySummaryData")
#xl.Application.Quit()
del xl
Expected Result - run vba function in already open excelfile.
Actual Result - just keeps running without error message. I guess code hangs.
xl.Application.Run(r"'DAILY PL ESTIMATE W NRPD RV2 v6_YK_v2.xlsm'!Module2.CopySummaryData")
While generating pdf from excel sheet i am getting below error:
ws.ExportAsFixedFormat(0, save_as)
File "<COMObject <unknown>>", line 5, in ExportAsFixedFormat
com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147024809), None)
Below is my code:
pythoncom.CoInitialize()
xlApp = client.Dispatch("Excel.Application")
logging.debug("Saving excel file {} to file {}".format(filename, save_as))
books = xlApp.Workbooks.Open(filename)
ws = books.Worksheets[0]
ws.Visible = 1
ws.ExportAsFixedFormat(0, save_as)
books.Close(True)
xlApp.Quit()
It works on my laptop where office 365 is installed however gives above error on another system with Microsoft office 2007 is installed.
Python version : python 2.7
openpyxl : 2.4.5
pywin32: 224
There is not enough documentation. It would be great help if someone can provide pointer to debug it and understand the error.
I had the same error while using xlwings for interacting with Excel. xlwings also use win32com clients in the backend.
I think it is not an Excel version issue.
I realized that this error pops up whenever the code is executed and the excel file (containing data) is not in focus. In order to resolve the issue, I simply select the file which is being processed and run the code and it always works for me.
I have found this related article: Python Interactions with Excel Macros
The code there is for python 2. The most important part is that closing the workbook and quitting the app resulted in remained excel workbooks hiddenly open in the background therefore when you want to open the workbook with Excel it can be open for reading only. To completely close all threads do this at the end (Python 3):
books.Close(True)
xlApp.quit()
xlApp = None
del xlApp
This way no threads remains and workbook(s) may be open for writing, can be saved...
This may also help in general error code decryption, in Python prompt:
import win32api
win32api.FormatMessage([ERRORCODEHERE])
for example:
import win32api
win32api.FormatMessage(-2147352567)
Which may give you more hints on the error (for me it did not).
I found the error to be raised when
wrong sheet name is given, so the excel file does not contain such
worksheet
while the script is running and performing tasks on the given
worksheet it loses somehow the focus. It may happen if you open or
just click on an excel file meanwhile the script is running, or you
open several workbooks with the script and it gets lost somehow.
Excel and python api should not have issues to work paralelly, but for me it did somehow.
Make everything step by step: open file->process->close then next...
All in short, check your code and worksheet names first, then go for simplified steps.
I am currently trying to create a program that scans a CSV file and searches entries in the file using the BING API, the results are then pasted into a spreadsheet.
Part of this macro involves also pasting onto the spreadsheet what term is being searched, so I am effectively copying an entry from the CSV into a spreadsheet, which sounds pointless but serves a vital role.
My CSV looks like this:
EntryNumber Name Company TitleNumber
123 john hsbc 5555
124 chris ford 6666
125 adam apple 7777
I use Pandas to extract the data from the CSV by iterating it through it row by row, using this code:
for index,row in df.iterrows():
entrynumber = row['EntryNumber']
name = row['Name']
company = row['Company']
title = row['TitleNumber']
Then I try and write one of the variables to a cell in the spreadsheet using xlsxwriter:
worksheet.write(row, col, entrynumber)
However this generates a type error, the traceback is below:
Traceback (most recent call last):
File "CSVtest.py", line 68, in <module>
worksheet.write(row, col, entrynumber)
File "/usr/local/lib/python3.5/site-packages/xlsxwriter/worksheet.py", line 57, in cell_wrapper
int(args[0])
File "/usr/local/lib/python3.5/site-packages/pandas/core/series.py", line 92, in wrapper
"{0}".format(str(converter)))
TypeError: cannot convert the series to <class 'int'>
Exception ignored in: <bound method Workbook.__del__ of <xlsxwriter.workbook.Workbook object at 0x1088118d0>>
Traceback (most recent call last):
File "/usr/local/lib/python3.5/site-packages/xlsxwriter/workbook.py", line 148, in __del__
Exception: Exception caught in workbook destructor. Explicit close() may be required for workbook.
No idea why this is happening, I've tried converting the variables to strings but the error still pops up, anyone got any ideas?
Any help is greatly appreciated :) Thanks.
Hey everyone I figured out a solution incase anyone else is as stupid as me to make the same mistake.
Basically, as I was using XLSXWRITER I had a variable called 'row' to tell the module where to start writing data to the spreadsheet.
In my haze I completely forgot that I had also used that same name when I was iterating over the CSV file using PANDAS, using the code:
for index,row in df.iterrows():
Obviously this caused some sort of error as Python got mixed up between the two.
Anyway its unlikely but hopefully this can help someone who makes a similar mistake while learning!
I am trying to open a .xlsx file with Openpyxl, using the "Optimized reader" tips from the documentation :
# -*- coding: iso-8859-1 -*-
from openpyxl import load_workbook
wb = load_workbook(filename = r'/path/to/the/file.xlsx', use_iterators = True)
This give me the following error :
Traceback (most recent call last):
File "/home/me/test.py", line 5, in <module>
wb = load_workbook(filename = r'/path/to/the/file.xlsx', use_iterators = True)
File "/usr/local/lib/python2.6/dist-packages/openpyxl/reader/excel.py", line 151, in load_workbook
_load_workbook(wb, archive, filename, read_only, keep_vba)
File "/usr/local/lib/python2.6/dist-packages/openpyxl/reader/excel.py", line 240, in _load_workbook
wb._named_ranges = list(read_named_ranges(archive.read(ARC_WORKBOOK), wb))
File "/usr/local/lib/python2.6/dist-packages/openpyxl/reader/workbook.py", line 160, in read_named_ranges
named_range.scope = workbook.worksheets[int(location_id)]
IndexError: list index out of range
I also tried using flags (keep_vba = True|False, guess_types = True|False, data_only = True|False) with every combination. Same error.
The .xlsx file I am trying to open has 13 worksheets, there is no worksheet with more than 200 row, so I suppose this is not a size problem.
I can't edit anything on this .xlsx file, I don't have permission, this is a readonly file for me.
I am using Python 2.6 on a Debian Squeeze 64 bits and the version of Openpyxl is 2.1.0.
If I try to open an other file (an empty test file), it works fine (no error triggered, the script carry on).
So I suppose the question is : what is wrong with the .xlsx file I am trying to open ?
The problem is related to the defined names / ranges in use. I've seen it an another file but not yet sure quite what's triggering it. Can you please submit a bug, preferably with a sample file, as this will make tracking the problem down a lot easier.
The 2.1 branch should contain a fix for this if you can try a checkout. As far as I can tell the issue is related to the use of defined names from other workbooks or when using some of the reserved names for print areas, etc. Such definitions are likely lost when the file is processed by openpyxl but shouldn't affect the data itself