Running .exe to execute batch file written in Python (Novice Programmer) - python

I wrote a Python script to prompt users for a spreadsheet to rename photos automatically based on the column called "Rename_Code" in the spreadsheet. The column is extracted and saved as a batch file, called "Rename_Code.bat". Below is the script:
import pandas as pd from tkinter.filedialog
import askopenfilename
#prompt user to browser excel sheet and load the spreadsheet in python
xl = pd.ExcelFile(askopenfilename() , index_col=None)
# load a sheet into a dataframe called df1
df1 = xl.parse('Sheet1')
# assign "Rename Code" column as rename_col
rename_col = df1['Rename_Code']
# extract the column and write as a batch file
rename_col.to_csv('Rename_Code.bat', index=False)
from subprocess import Popen p = Popen("Rename_Code.bat", cwd=r"C:\Users\username\Documents\XXXXX") stdout, stderr = p.communicate()
What I am trying to do is convert this script (in .pyw format) into an .exe so that anyone can use it without having Python installed in their computers. I used py2exe to convert the script. However, it kicked an error when I double clicked on the .exe. It says "Failed to launch application".
I am wondering if there is something wrong with the script. Alternatively, is there a better way to execute this, perhaps with Window Services? If yes, how? I am a novice programmer, most of my learning in programming involves a lot of trial and error and research.
I truly appreciate your feedback and help!

Related

How to refresh all pivot table of an excel file using Python xlwings [duplicate]

I am trying to refresh a pivot table in excel upon data written by XLWINGS.
As I don't know how to do it directly from XLWINGS, I tried to use VBA.
Let's split my process in 2 steps:
Step1
I launch the python code from vba (my module name is "PosRep", the python code writtes back a range of data in a specified sheet thanks to xlwings.
Sub launchPython()
RunPython ("import PosRep; PosRep")
End Sub
Step 2
But as I don't know in advance the size of my newly created Range in Excel, I want to select it, add a new Name (NamedRange) and refresh my pivot (already linked to the NamedRange).
Sub SelectRange()
Worksheets("GPODump").Range("A1").Select
'...
End Sub
Both Subs work independently well. But I cannot manage to make them work in a raw. The following code:
Sub Main()
launchPython
SelectRange
End Sub
produces a VBA error "Select method of Range class failed" on the statement:
Worksheets("GPODump").Range("A1").Select
I presume there is a conflict with the XLWINGS VBA module but I can't figure out what it can be...
Anyone's help would be more than welcome !
Thx
The problem came from the VBA code. The following code works fine:
Sheets("GPODump").Select
Sheets("GPODump").Range("A1").Select
Maybe it's too late but you can do it within xlwings - this is what worked for me:
import xlwings as xw
# open excel App
app_excel = xw.App(visible = False)
# open the excel file, select the tab and the PivotTable to refresh
wbook = xw.Book( 'YourFile.xlsx' )
wbook.sheets['Tab1'].select()
wbook.api.ActiveSheet.PivotTables('PivotTableName').PivotCache().refresh()
I was looking how to solve this for Mac, here is how I did to refresh all pivot tables and etc:
wb.api.active_sheet.refresh_all(wb.api)
Hopes that this saves someone else time. Took me a while to figure it out.

Start python script from excel with input

I have a Python script (gui.py - a calculation program, written by somebody else). I try to run this from excel with input data from the same excel file. It works fine when I start the script as:
objShell.Run PythonExe & PythonScript3
In the python script I used the following to get f.ex data from H5 cell, works also fine:
import openpyxl
wb = openpyxl.load_workbook("01.xlsm")
ws = wb.active
mastNumber = ws['H5']
But I don't want to edit a lot in gui.py (have just simple changes) so I planned to use a 2nd script (caller.py) which gets the data from Excel, then I import this to gui.py and there I just use the variable from caller.py. It works also as long as I start gui.py directly. When I start it from Excel I get an error msg.
error msg
So as long as the flow is not Excel -> gui-py -> which imports caller to get data from same Excel file -everything works fine.
I am open to any solution for this problem or a completely new approach if there is better for somebody with limited programming skills.
Looking at the error, can you try putting complete path of the excel file at line wb = openpyxl.load_workbook("01.xlsm") instead of just 01.xlsm.

Python vba extract to get bin of macro

I am trying to add a vba_project to "Sheet1" of a workbook using python.
I am following XLSXWRITER documentation to get the bin of the VBA code from a different sheet which I would want to use in "Sheet1" of my new workbook.
I enter the below code in command prompt but I get the error: "'vba_extract.py' is not recognized as an internal or external command"
$ vba_extract.py Book1.xlsm
Extracted: vbaProject.bin
Can someone give me a step by step on how to extract the macro from old file as bin and then input into sheet1 of new workbook using python?
You have to tell the cmd you're running a python file.
Try this batch code:
cd C:\path\of\yourfile.py
python vba_extract.py Book1.xlsm
edit:
Added cd command, you have to be in the folder of the python file.
I figured this out today and just wanted to leave it here for any future people to use. This was so unbelievably frustrating to figure out how to do. If you are using the Pandas library, this is also relevant. Make sure to install xlsxwriter also.
1.Click on your windows start button and type 'cmd' and click on it to run the Command Prompt.
2.Once you have it open, you need to locate where the vba_extract.py file is. For me it was here:
C:\Users\yourusername\AppData\Local\Programs\Python\Python36-32\Scripts\vba_extract.py
3.Now, you need to get the path of the .xlsm file you want to take from. If you don't have a .xlsm file made. Make one. Here is an example:
C:\Users\yourusername\Desktop\excelfilename.xlsm
4.Now, back to the Command Prompt. This is exactly what you will type. You will take both items from steps 2 and 3 and combine then and hit enter. Here:
C:\Users\yourusername\AppData\Local\Programs\Python\Python36-32\Scripts\vba_extract.py C:\Users\yourusername\Desktop\excelfilename.xlsm
if it is successful, it will tell you this:
Extracted: vbaProject.bin
5.For this one I'm not sure. I assume that wherever your .xlsm file is where the .bin file will end up. For this example, it ended up on my desktop. It will have all the macros you created or had on the original .xlsm file.
C:\Users\yourusername\Desktop/vbaProject.bin
Here is an example of it being used in full code:
import pandas
import xlsxwriter
df_new = pd.read_csv('C:\\Users\\yourusername\\Desktop\\CSV1.csv')
writer = pd.ExcelWriter('C:\\Users\\yourusername\\Desktop\\CSV1.xlsx')
df_new.to_excel(writer, index = False, sheet_name = 'File Name', header = False)
pandaswb = writer.book
pandaswb.filename = 'C:\\Users\\yourusername\\Desktop\\newmacroexcelfile.xlsm')
pandaswb.add_vba_project(r'C:\Users\yourusername\Desktop/vbaProject.bin')
writer.save()

Use Python to Write VBA Script?

This might be a bit of a stretch, but is there a possibility that a python script can be used to create VBA in MS Excel (or any other MS Office product that uses VBA) using pythonwin or any other module.
Where this idea came from was pythons openpyxl modules inability to do column autowidth. The script I have creates a workbook in memory and eventually saves it to disc. There are quite a few sheets and within each sheet, there are quite a few columns. I got to thinking....what if I just use python to import a VBA script (saved somewhere in notepad or something) into the VBA editor in excel and then run that script from python using pythonwin.
Something like:
Workbooks.worksheets.Columns("A:Z").EntireColumn.Autofit
Before you comment, yes I have seen lots of pythonic examples of how to work around auto adjusting columns in openpyxl, but I see some interesting opportunities that can be had utilizing the functionality you get from VBA that may not be available in python.
Anyways, I dug around the internet a bit and I didn't see anything that indicates i can, so i thought I'd ask.
Cheers,
Mike
Yes, it is possible. You can start looking at how you can generate a VBA macro from VB on that Microsoft KB.
The Python code below is illustrating how you can do the same ; it is a basic port of the first half of the KB sample code:
import win32com.client as win32
import comtypes, comtypes.client
xl = win32.gencache.EnsureDispatch('Excel.Application')
xl.Visible = True
ss = xl.Workbooks.Add()
sh = ss.ActiveSheet
xlmodule = ss.VBProject.VBComponents.Add(1) # vbext_ct_StdModule
sCode = '''sub VBAMacro()
msgbox "VBA Macro called"
end sub'''
xlmodule.CodeModule.AddFromString(sCode)
You can look at the visible automated Excel macros, and you will see the VBAMacro defined above.
The top answer will only add the macro, if you actually want to execute it there is one more step.
import win32com.client as win32
xl = win32.gencache.EnsureDispatch('Excel.Application')
xl.Visible = True
ss = xl.Workbooks.Add()
xlmodule = ss.VBProject.VBComponents.Add(1)
xlmodule.Name = 'testing123'
code = '''sub TestMacro()
msgbox "Testing 1 2 3"
end sub'''
xlmodule.CodeModule.AddFromString(code)
ss.Application.Run('testing123.TestMacro')
Adding a module name will help deconflict from any existing scripts.

Calling python script from excel/vba

I have a python code that reads 3 arguments (scalars) and a text files and then returns me a vector of double. I want to write a macro in vba to call this python code and write the results in one of the same excel sheet. I wanted to know what was the easiest way to do it, here are some stuffs that I found:
call the shell() function in vba but it doesn't seem so easy to get the return value.
register the python code as a COM object and call it from vba--> i don't know how to do that so if you have some examples it would be more than welcome
create a custom tool in a custom toolbox, in vba create a geoprocessing object and then addtoolbox and then we can use the custom tool directly via the geoprocessing object but this is something as well that I don't know how to do..
Any tips?
Follow these steps carefully
Go to Activestate and get ActivePython 2.5.7 MSI installer.
I had DLL hell problems with 2.6.x
Install in your Windows machine
once install is complete open Command Prompt and go to
C:\Python25\lib\site-packages\win32comext\axscript\client
execute \> python pyscript.py
you should see message Registered: Python
Go to ms office excel and open worksheet
Go to Tools > Macros > Visual Basic Editor
Add a reference to the Microsoft Script control
Add a new User Form. In the UserForm add a CommandButton
Switch to the code editor and Insert the following code
Dim WithEvents PyScript As
MSScriptControl.ScriptControl
Private Sub CommandButton1_Click()
If PyScript Is Nothing Then
Set PyScript = New MSScriptControl.ScriptControl
PyScript.Language = "python"
PyScript.AddObject "Sheet", Workbooks(1).Sheets(1)
PyScript.AllowUI = True
End If
PyScript.ExecuteStatement "Sheet.cells(1,1).value='Hello'"
End Sub
Execute. Enjoy and expand as necessary
Do you have to call the Python code as a macro? You could use COM hooks within the Python script to direct Excel and avoid having to use another language:
import win32com.client
# Start Excel
xlApp = win32com.client.Dispatch( "Excel.Application" )
workbook = xlApp.Workbooks.Open( <some-file> )
sheet = workbook.Sheets( <some-sheet> )
sheet.Activate( )
# Get values
spam = sheet.Cells( 1, 1 ).Value
# Process values
...
# Write values
sheet.Cells( ..., ... ).Value = <result>
# Goodbye Excel
workbook.Save( )
workbook.Close( )
xlApp.Quit( )
Here is a good link for Excel from/to Python usage:
continuum.io/using-excel
mentions xlwings, DataNitro, ExPy, PyXLL, XLLoop, openpyxl, xlrd, xlsxwriter, xlwt
Also I found that ExcelPython is under active development.
https://github.com/ericremoreynolds/excelpython
2.
What you can do with VBA + Python is following:
Compile your py scripts that take inputs and generate outputs as text files or from console. Then VBA will prepare input for py, call the pre-compiled py script and read back its output.
3.
Consider Google Docs, OpenOffice or LibreOffice which support Python scripts.
This is assuming that available options with COM or MS script interfaces do not satisfy your needs.
This is not free approach, but worth mentioning (featured in Forbes and New York Times):
https://datanitro.com
This is not free for commercial use:
PyXLL - Excel addin that enables functions written in Python to be called in Excel.
Updated 2018
xlwings is a BSD-licensed Python library that makes it easy to call Python from Excel and vice versa.
Scripting: Automate/interact with Excel from Python using a syntax that is close to VBA.
Macros: Replace your messy VBA macros with clean and powerful Python code.
UDFs: Write User Defined Functions (UDFs) in Python (Windows only).
Installation
Quickstart
There's a tutorial on CodeProject on how to do this.
See http://www.codeproject.com/Articles/639887/Calling-Python-code-from-Excel-with-ExcelPython.
Another open source python-excel in process com tool.
This allows executing python scripts from excel in a tightly integrated manner.
https://pypi.python.org/pypi/Python-For-Excel/beta,%201.1

Categories

Resources