Target specific Excel workbook by name with Python with win32com - python

If I have multiple Excel workbooks open on Windows 10, and I'm using win32com in Python, is there a way to choose a workbook by name? So far, I have been using:
ExcelApp = win32com.client.GetActiveObject('Excel.Application')
wb = ExcelApp.Workbooks(2)
but that requires the correct workbook to be the second one. Is there some way I can do it by name or filepath instead? I tried:
ExcelApp = win32com.client.GetActiveObject('Excel.Application')
wb = ExcelApp.Workbooks.Open(os.path.join(os.path.dirname(__file__), 'myworkbook.xlsm'))
but this does not work either if I have multiple Excel workbooks open. It ends up choosing the wrong workbook since later on, when it is looking for a specific sheet by name, it cannot find it.
If I try:
ExcelApp = win32com.client.GetActiveObject('Excel.Application')
wb = ExcelApp.Workbooks('My Workbook Name')
I get this:
Traceback (most recent call last):
File "E:\Archives\mypyscript.py", line 79, in <module>
wb = ExcelApp.Workbooks('My Workbook Name')
File "C:\Users\username\AppData\Local\Temp\gen_py\3.8\00020813-0000-0000-C000-000000000046x0x1x9\Workbooks.py", line 198, in __call__
ret = self._oleobj_.InvokeTypes(0, LCID, 2, (13, 0), ((12, 1),),Index
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147352565), None)```

Related

Error while updating excel sheet using xlwings with pandas dataframe

When I run this code, the excel sheet is updated with values but I am getting the following error messages. Please help me.
import glob
from operator import index
import pandas as pd
import numpy as np
import xlwings as xw
master_file = Master.xlsm'
ytd_file = ytd_sales.xlsx'
df1 =pd.read_excel(master_file, sheet_name='Cap', header=52)
df2 = pd.read_excel(ytd_file, sheet_name= 'Sub App', header=2)
df_master_subApp = df1.head(106)
df_ytd_subApp = df2.head(55)
wb1 = xw.Book(master_file)
ws1 = wb1.sheets['Cap']
df_subApp = pd.merge(df_master_subApp, df_ytd_subApp[['Item no.', 'NS']], on='Item no.', how='left')
df_subApp["January"] = df_subApp["NS"] # This will copy the data from 'Amount' column to 'JAN' column
df_subApp.drop("NS", axis=1, inplace=True)
ws1.range('L53:L159').options(transpose = False, index=False, numbers=int).value = df_subApp["January"]
Error Messages:
File "c:\Users\%usename%\Documents\PythonAutomation\FinMonEndReportAutomate\merge_fin_master_ytd_file.py", line 75, in <module>
ws1.range('L53:L159').options(transpose = False, index=False, numbers=int).value = df_subApp["January"].values # This code will fill the "January" column in master sheet
File "C:\Users\%usename%\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\xlwings\main.py", line 2052, in value
conversion.write(data, self, self._options)
File "C:\Users\%usename%\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\xlwings\conversion\__init__.py", line 48, in write
pipeline(ctx)
File "C:\Users\%usename%\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\xlwings\conversion\framework.py", line 66, in __call__
stage(*args, **kwargs)
File "C:\Users\%usename%\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\xlwings\conversion\standard.py", line 74, in __call__
self._write_value(ctx.range, ctx.value, scalar)
File "C:\Users\%usename%\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\xlwings\conversion\standard.py", line 62, in _write_value
rng.raw_value = value
File "C:\Users\%usename%\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\xlwings\main.py", line 1645, in raw_value
self.impl.raw_value = data
File "C:\Users\%usename%\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\xlwings\_xlwindows.py", line 859, in raw_value
self.xl.Value = data
File "C:\Users\%usename%\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\xlwings\_xlwindows.py", line 109, in __setattr__
return setattr(self._inner, key, value)
File "C:\Users\%usename%\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\win32com\client\__init__.py", line 595, in __setattr__
self._oleobj_.Invoke(*(args + (value,) + defArgs))
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2146827284), None)

What is the best way to run an Excel macro with Python3?

I am trying to write to a macro enabled excel file (xlsm) and then run a macro that is dependent on the cell my script is writing to. For clarity I am on a windows machine, I am not the admin and I am working with python3.8.0
I have a file called write.py, in this file it writes yesterdays date to the A1 cell unless it is Monday then it writes Fridays date. After it writes the date I would like to run a macro that uses that cell/date to do something.
So far I can write yesterdays date and I can run a macro but I cannot do them in the same file. I tried separating the files and executing the macro from the write.py file but that gave me the same error.
Here is my code for the write.py file that writes yesterdays date to the A1 cell of an xlsm file:
from datetime import date
from datetime import timedelta
import openpyxl
path = "C:/Users/project/file.xlsm"
# loads the workbook into a var
book = openpyxl.load_workbook(path)
sheet = book["Sheet2"] # loads a specific sheet by name into a var
a1 = sheet['A1'] # loads a cell into a var
# testing
print(book.sheetnames)
print(a1.value)
# Get yesterdays date unless its a Monday then get Fridays date
today = date.today()
if date.today().weekday() == 0:
yesterday = today - timedelta(days=today.weekday()) + timedelta(days=4, weeks=-1)
else:
yesterday = today - timedelta(days = 1)
yestFormat = (yesterday.strftime("%x")) # formatting the date
# setting the value of the A1 cell to the yesterFormat var
sheet.cell(row=1,column=1,value=yestFormat)
book.save(path)
# This file is supposed to run the macro
exec(open('runMacro.py').read())
Here is the code for the second file that is supposed to run the macro, I have also had this code in the write.py file and I run into the same problems
import xlwings as xw
# loads the workbook into workbook var then loads a specific sheet into worksheet var
wb = xw.Book(r'C:/Users/project/file.xlsm')
wb.macro('test_macro')()
wb.save(r'C:/Users/project/file.xlsm')
When I run the write.py file with the exec command commented out it works and writes the date to the cell. So there is something wrong with the way I am executing the macro. Something I have noticed is if the excel file is open then the write.py file will not work, and the runMacro.py file opens the excel doc when I run it. I think it has something to do with how it is saving or opening but I have read through xlwings documentation and I am doing what it says on how to save, so I am not sure. Hoping there is a better way, thanks for any feedback.
Edit:
Sorry I forgot to add the error I am getting. I have changed the file paths for privacy reasons so there might be some inconsistencies there.
Traceback (most recent call last):
File "C:\Users\project\venv\lib\site-packages\xlwings\_xlwindows.py", line 466, in __call__
return Book(xl=self.xl(name_or_index))
File "C:\Users\project\lib\site-packages\xlwings\_xlwindows.py", line 156, in __call__
v = self._inner(*args, **kwargs)
File "C:\Users\username\AppData\Local\Temp\gen_py\3.8\00020813-0000-0000-C000-000000000046x0x1x8.py", line
39136, in __call__
ret = self._oleobj_.InvokeTypes(0, LCID, 2, (13, 0), ((12, 1),),Index
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147352565), None)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\project\code\venv\lib\site-packages\xlwings\main.py", line 3873, in open
impl = self.impl(name)
File "C:\Users\project\venv\lib\site-packages\xlwings\_xlwindows.py", line 468, in __call__
raise KeyError(name_or_index)
KeyError: 'sample.xlsm'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:/Users/project/test.py", line 35, in <module>
exec(open('test2.py').read())
File "<string>", line 4, in <module>
File "C:\Users\username\venv\lib\site-packages\xlwings\main.py", line 547, in __init__
impl = app.books.open(fullname, update_links, read_only, format, password, write_res_password,
File "C:\Users\username\venv\lib\site-packages\xlwings\main.py", line 3879, in open
impl = self.impl.open(fullname, update_links, read_only, format, password, write_res_password,
File "C:\Users\username\venv\lib\site-packages\xlwings\_xlwindows.py", line 484, in open
return Book(xl=self.xl.Open(fullname, update_links, read_only, format, password, write_res_password,
File "C:\Users\username\venv\lib\site-packages\xlwings\_xlwindows.py", line 66, in __call__
v = self.__method(*args, **kwargs)
File "C:\Users\username\AppData\Local\Temp\gen_py\3.8\00020813-0000-0000-C000-000000000046x0x1x8.py", line
39013, in Open
ret = self._oleobj_.InvokeTypes(1923, LCID, 1, (13, 0), ((8, 1), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17)),Filename
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', "Excel cannot open the file 'sample.xlsm' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file.", 'xlmain11.chm', 0, -2146827284), None)

xlwings error: not opening excel workbook getting an error upon call wb.open

xlwings works fine on my computer, but when I try to transfer the same set up to another computer it seems to not open correctly giving me this error
Traceback (most recent call last):
File "C:\Users\base7268\AppData\Local\Programs\Python\Python37\lib\site-packages\xlwings\_xlwindows.py", line 432, in __call__
return Book(xl=self.xl(name_or_index))
File "C:\Users\base7268\AppData\Local\Programs\Python\Python37\lib\site-packages\xlwings\_xlwindows.py", line 152, in __call__
v = self._inner(*args, **kwargs)
File "C:\Users\base7268\AppData\Local\Programs\Python\Python37\lib\site-packages\win32com\client\dynamic.py", line 197, in __call__
return self._get_good_object_(self._oleobj_.Invoke(*allArgs),self._olerepr_.defaultDispatchName,None)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147352565), None)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\base7268\AppData\Local\Programs\Python\Python37\lib\site-packages\xlwings\main.py", line 2776, in open
impl = self.impl(name)
File "C:\Users\base7268\AppData\Local\Programs\Python\Python37\lib\site-packages\xlwings\_xlwindows.py", line 434, in __call__
raise KeyError(name_or_index)
KeyError: 'output2019-06-03.11-40timeseries_5-31-2019scrubbed.xlsx'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "Computation.py", line 157, in <module>
xwWb = xw.Book("output" + timeName + os.path.split(file_path)[1])
File "C:\Users\base7268\AppData\Local\Programs\Python\Python37\lib\site-packages\xlwings\main.py", line 488, in __init__
impl = app.books.open(fullname).impl
File "C:\Users\base7268\AppData\Local\Programs\Python\Python37\lib\site-packages\xlwings\main.py", line 2787, in open
impl = self.impl.open(fullname)
File "C:\Users\base7268\AppData\Local\Programs\Python\Python37\lib\site-packages\xlwings\_xlwindows.py", line 443, in open
return Book(xl=self.xl.Open(fullname))
File "C:\Users\base7268\AppData\Local\Programs\Python\Python37\lib\site-packages\xlwings\_xlwindows.py", line 63, in __call__
v = self.__method(*args, **kwargs)
File "<COMObject <unknown>>", line 8, in Open
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', 'Open method of Workbooks class failed', 'xlmain11.chm', 0, -2146827284), None)
Here is some simplified code where none of the data changing is occurring. Using ospath absolute does not help with the error. Both systems run the same 64 bit operating system and 32 bit excel. Yet the error persists on the second machine. There is no real difference I can understand that would give me an error on the 2nd system over the first one. Both machines are PCs
import xlrd
import openpyxl
import xlwings as xw
from xlwings import constants
import os
import tkinter as tk
from tkinter import filedialog
import datetime
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()
print(file_path)
start = time.time()
wb = openpyxl.load_workbook(file_path)
Returns = wb['Prices']
newWs = wb.create_sheet()
newWs.title = "NominalDailyReturns"
benchWS = wb.create_sheet()
benchWS.title = "ActiveDailyReturns"
thirdWs = wb.create_sheet()
thirdWs.title = "RawAnalysis"
thirdWs.column_dimensions["A"].width = 32
name4 = thirdWs.title
print("halfway")
print(os.path.split(file_path))
print("output" + timeName + os.path.split(file_path)[1])
wb.save("output" + timeName + os.path.split(file_path)[1])
xwWb = xw.Book(os.path.abspath("output" + timeName + os.path.split(file_path)[1]))
XnewWs = xwWb.sheets['NominalDailyReturns']
xwWb.save()
xwWb.close()
wb = openpyxl.load_workbook("output" + timeName + os.path.split(file_path)[1])
benchWS = wb['ActiveDailyReturns']
wb.save("output" + timeName + os.path.split(file_path)[1])
xwWb = xw.Book("output" + timeName + os.path.split(file_path)[1])
XthirdWs = xwWb.sheets['RawAnalysis']
xwWb.save()
xwWb.close()
I figured out the problem with my code. When I used openpyxl to edit my excel data, one of the formulas was subtracting a word from a number, raising an error and corrupting the excel file. Then xlwings tried to open a corrupted file, and it failed on me.
So the solution is to not save a corrupted excel file and expect xlwings to open it.

How to slice Excel data using win32com in Python (3.6)

I have data in Excel that I want to split.
Here is my code
import win32com.client
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = True
wb = excel.Workbooks.Open('C:\\Users\\a\\Desktop\\bin256.xlsx')
ws = wb.ActiveSheet
input_number = ws.Range('U4:U15363')
number = [input_number[i:i+60] for i in range(0,len(input_number),60)]
But I get this error:
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
number = [input_number[i:i+60] for i in range(0,len(input_number),60)]
File "<pyshell#13>", line 1, in <listcomp>
number = [input_number[i:i+60] for i in range(0,len(input_number),60)]
File "C:\Users\a\AppData\Local\Programs\Python\Python36-32\lib\site-packages\win32com\client\dynamic.py", line 256, in __getitem__
return self._get_good_object_(self._oleobj_.Invoke(dispid, LCID, invkind, 1, index))
TypeError: Objects of type 'slice' can not be converted to a COM VARIANT
How can I fix that? Thanks in advance.
Did you just want to open excel?
Maybe you can try pandas
import pandas as pd
file_path=r'E:\download\tmp\test.xlsx'
file_path='./tmp/test.xlsx'
df_name.to_excel(file_path,sheet_name='Sheet1',index=False)

Add method of OLEObjects class failed

I'm trying to add an Excel Document within another Excel Document using OLEObjects in Python, but I'm getting this error:
d:\Python\PythonReport>d:/Python27/python.exe genDP.py d:/Python/PythonReport/ATP.xlsx
Traceback (most recent call last):
File "genDP.py", line 219, in <module>
add_ATP_WorkBook(OutputBook, sys.argv[1])
File "genDP.py", line 212, in add_ATP_WorkBook
oleObjects.Add(ClassType=None, Filename=file, Link=False, DisplayAsIcon=False, Left=0, Top=0, Width=50, Height=50)
File "<COMObject OLEObjects>", line 6, in Add
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Office Excel', u'Add method of OLEObjects class failed', u'C:\\Program Files (x86)\\Microsoft Office\\Office12\\1033\\XLMAIN11.CHM', 0, -2146827284), None)
What is strange is the fact that it works well for other files: I could easily add a text document as OLEObject, but when I try with an Excel Document I get that error.
This is the code:
def add_ATP_WorkBook(OutputBook, file):
ExcelApp = win32com.client.Dispatch("Excel.Application")
ExcelApp.visible = 1
workbook = ExcelApp.Workbooks.open(str(os.path.abspath(os.path.dirname(sys.argv[0])))+"\DVPR Report.xls")
oleObjects = workbook.ActiveSheet.OLEObjects()
oleObjects.Add(ClassType=None, Filename=file, Link=False, DisplayAsIcon=False, Left=0, Top=0, Width=50, Height=50)
workbook.Worksheets('Recognition Rate').Activate()

Categories