GithubHelp home page GithubHelp logo

ericremoreynolds / excelpython Goto Github PK

View Code? Open in Web Editor NEW
228.0 35.0 59.0 785 KB

An open source, easy to use interface for calling Python code from Excel

Home Page: http://ericremoreynolds.github.io/excelpython

License: BSD 2-Clause "Simplified" License

Python 15.20% Visual Basic 28.81% C++ 48.68% Inno Setup 7.30%

excelpython's Introduction

Notice : ExcelPython has been integrated into xlwings! Going forwards ExcelPython will be no longer be actively maintained and any further development work will take place within the context of xlwings.

ExcelPython v2

Write Excel user-defined functions and macros in Python!

from xlpython import *

@xlfunc
@xlarg("x", "nparray", 2)
@xlarg("y", "nparray", 2)
def matrixmult(x, y):
    return x.dot(y)

image

Check out the tutorials to get started! The only prerequisites are Excel and Python (2.6 - 3.x) with PyWin32 installed.

About ExcelPython

ExcelPython is a lightweight, easily distributable library for interfacing Excel and Python. It enables easy access to Python scripts from Excel VBA, allowing you to substitute VBA with Python for complex automation tasks which would be facilitated by Python's extensive standard library while sparing you the complexities of Python COM programming.

Do you like ExcelPython and find it useful? If so please consider donating something to support its continued development and get your name on the donor list!

Click here to lend your support to: ExcelPython and make a donation at pledgie.com !

Help me!

Check out the docs folder for tutorials to help you get started and links to other resources. Failing that, try the issues section or the discussion forum on SourceForge.

If you still don't find your answer, need more help, find a bug, think of a useful new feature, or just want to give some feedback by letting us know what you're doing with ExcelPython, please go ahead and create an issue ticket!

excelpython's People

Contributors

ericremoreynolds avatar tusky avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

excelpython's Issues

"error in the formula" window

Hi:
I am just starting but I have been through all the setup entertainment there is ! :-)

Here is the current challenge:

I start to enter the formula and before I enter the parenthesis a tiny window shows up with tinier round circle with a fx sign followed by the DoubleSum letters. All good till I put the (1, 2) and click ENTER.

Now I get the "error in the formula" window.

What have I done since install:

  1. Because I noticed that the .xlsm file had a exclamation sign on its graphic I spent quite a bit of time figuring out the trust permissions for Excel macros, and now I left everything so open that I can be taken by any malicious macros.
  2. I checked the location of the xlpython.xlam file in the Excel subdirectory 14 for the permanent install, Is there, and the smily along with the Fx import show up by itself after I restart the machine and Excel.

I must be close ! :-)

I wonder if it could be a Python path problem because the scrip is getting into Excel fine as a function. Thus the problem may be the execution of the script:

  • the call to the Python interpreter,
  • or the Python response

Now since I am a newbie I am just speculating

Any help will be much appreciated,

Adolfo

'1004 runtime error'

Hello, I have installed the excelphyton and I am running into this following error in VBA.
not_present:
On Error GoTo 0
This line is where it stops running
-> wb.VBProject.VBComponents.Import wb.Path + "\xlpython.bas"

Can anyone help me to fix this problem? Thanks!

Using ExcelPython with iPython

A few users have mentioned the desire to have modules auto-reload, which certainly would be nice when developing calculations and other things to go along with that. It occurred to me that we should just be able to use ipython, instead of pythonw, and have things interface that way, and then use a special excel-python profile to activate the autoreload module for ipython.

first I created an ipython profile by running,
ipython profile create excelpython

Then in the ipython_profile.cfg file in the newly created profile_excelpython folder, I put the two lines:

c.InteractiveShellApp.extensions = ['autoreload']
c.InteractiveShellApp.exec_lines = ['%autoreload 2']

using this profile in a command line works as expected, auto-reloading modules on the fly.

Then I went into the excelpython config file and I changed line 25 of the xlpython.cfg file from:
Command = pythonw.exe -u "$(ConfigDir)\xlpyserver.py" $(CLSID)
to
Command = ipython.exe --profile=excelpython "$(ConfigDir)\xlpyserver.py" $(CLSID)

It launches correctly, and will do python calculations as expected (at least in simple cases), although now it pops up a persistent window for the python runtime.

However, the auto-reload feature is not working as expected, and modules are not re-loading as they do when working in one of the standard ipython interfaces.

Is there an intrinsic reason this won't work, or maybe this is just a setting or a small change somewhere?

Long python process apparently timing out

I have a long-running python process that works independently and works properly in Excel when runtime is under 90 seconds or so. If the runtime is sufficiently long, Excel generates an alert - "Microsoft Excel is waiting for a another application to complete an OLE action".

This is pretty clearly a timeout, but I can't figure out how to set a longer timeout - maybe 600 seconds. Is it possible to set a longer timeout for ExcelPython

Portable Python

Hi,

Excel shows ans error when I try type ?PyStr(PyEval("1+2")) in the immediate window : File not found: ExcelPython26.dll
Regards.

Py.Var is rounding my resulting tuple of Decimals

HI Eric,

I have a python function which returns a tuple of Decimals e.g.
(Decimal('4.96218411552347000000'), Decimal('4.95415534319262000000'), Decimal('4.94349678841657000000'), Decimal('4.93623882952235000000'))

When this is returned to Excel through a UDF, the Py.Var VBA function appears to round the results leaving only 4 decimal places.

Is there a way for it to return the full precision?

Thanks

xlpython.log file is locked

Hi Eric,

I'm running two separate excel sessions in the same folder, which both use the excelpython functionality. I'm finding that when I try to run some of the python functionality from either session, I have to end the pythonw.exe process or I get a "could not open .....xlpython.log for redirection" error.
Is there a way to avoid this?

Thanks,

Charlie

Updating links to revised Python code

Working through the tutorials, it seems that the "Import Python UDFs" button automatically generates new VBA code, writing over whatever we had before. Is there any way to reload the Python code without changing the VBA in any way? At the moment I am having to close Excel and re-open.

Optional arguments VBA & Python

Hi,

If I have a python function such as this:

@xlfunc
def test(dte, str = None):
if str is None:
c = dte.strftime("%Y-%m-%d") + "Hello"
else:
c = dte.strftime("%Y-%m-%d") + "Goodbye"
return c

Would would I call this from an excel udf?

I have a vba function as:

function test(dte,optional str = Empty)
etc etc

Thanks,

Charlie

import UDFs from one central python repository

Hi Eric,

We use many spreadsheets which use the excelpython udf funcationality. Many of these UDFs are the same in each spreadsheet (e.g. a function which does a dateAdd...etc,etc). Is there a way to make the excelpython add-in reference a single python module for importing udfs...as well as any udfs which are defined in the workbooks own .py module? It would decrease the set-up faff for a new workbook.

Any ideas on the quickest way to do this?

Thanks,

Charlie

VBA problems

Must be something wrong with my configuration - have been able to run macros as explained in your tutorials, but the moment I try to do anything in my VBA immediate window, I get a Run-time error '438'. I am able to step through all the code, but in the end, it throws up the error. Great product, but I need to be able to run it in VBA as well. Thanks,
Pradeep

xlpython32-2.0.6.dll not found

Hi Eric!

I'm following the tutorial and I'm facing a problem. When I click the "import python UDFs" I get a run-time error '53', file not found xlpython32-2.0.6.dll. I'm using windows xp 64bits with a portable version of python, the file xlpython32-2.0.6.dll is inside the folder xlpython. The folder structure is like this (the brackets are just for clarification)

My Documents
|--py_excel (folder)
|--testpy.xls
|--testpy.py
|--xlpython (folder)
|--init.py
|--fix_anaconda_pywin32.py
|--xlpyserver.py
|--xlpython (bas file)
|--xlpython.cfg
|--xlpython32-2.0.6.dll
|--xlpython64-2.0.6.dll
|--xlpython_v1back

The add-in is installed in c:\PortableApps\excelpython and python 2.7.6 is in C:\PortableApps\WinPython-32bit-2.7.6.4\python-2.7.6. The python path is added to the PATH variable (from a cmd windows I can run python) through a user variable.

I have not change the xlpython.cfg file.

Don't know if is of interest: I've checked the excel macro (automatically created by the add-in) and the XLPyLoadDLL works correctly and yes: the right path/file is passed to LoadLibrary. And, finally, everytime that I load the testpy.xls, the add-in complains that the file is not ready and I have to launch the "Setup ExcelPython" macro.

Thanks in advance for your help!

Does ExcelPython work with Excel 2003?

The quickstart page says ExcelPython works with Excel versions >=2003. However I could not find a .xla file in any versions. Excel 2003 will not open .xlam files. I tried converting the .xlam file from 2.08 to .xla in Excel 2013 and then installing it in Excel 2003. Although Excel 2003 added the Add-in to the available add-ins, there is no menu item for Xlpython and I do not see any way to import the UDF.

Please advise,
Thanks!

DLL not found

new issue created from comment #1 by @nmaravich

Hi all - sorry for the Noob complaint, but I am getting the dreadful .dll not found at the py - immediate window test. I have anaconda 64 bit and excel 2010 also 64 bit. I removed the .dll and tried all of the updated .exe as well as manually drooped the .dlll in the sys/32 folder. Let me now if there are a series of steps that I can take to double check that I did not do something wrong. Thanks!

Error importing Python UDFs (run-time error 1000)

Hello,

When I click Import Python UDFs, I get run-time error 1000.

The problem seem to be with fix_anaconda_pywin32.py, which cannot fine the moldule named _win32sysloader.

This is what the log file says:

Traceback (most recent call last):
File "C:\Hydraulic\xlpython\xlpyserver.py", line 2, in
import fix_anaconda_pywin32
File "C:\Hydraulic\xlpython\fix_anaconda_pywin32.py", line 2, in
import _win32sysloader
ImportError: No module named _win32sysloader

Programmatic access to visual basic project not trusted

When I go to the excelpython tab on the worksheet created for installation and press the setup excelpython button, I get a dialog box:
-install runtime in the folder and
-setup this workbook to interact with python.
When I clisk yes, I get an error message: programmatic access to visual basic project not trusted
and if I then choose debug, it shows the following line:

wb.VBProject.VBComponents.Import wb.Path + Application.PathSeparator + "xlpython" + Application.PathSeparator + "xlpython.bas"

How can I proceed?

VBA7 64bit Excel2013 Issue

I am using Excel 2013 64 bit.

After setting up ExcelPython with the "Setup ExcelPython" button I am getting the following error:
capture

I think the syntax should be something like that (twisting "PtrSafe" and "Function"):

If VBA7 Then

    #If Win64 Then
            Const XLPyDLLName As String = "xlpython64-2.0.6.dll"
            Declare PtrSafe Function XLPyDLLActivate Lib "xlpython64-2.0.6.dll" (ByRef result As Variant, Optional ByVal config As String = "") As Long
            Declare PtrSafe Function XLPyDLLNDims Lib "xlpython64-2.0.6.dll" (ByRef src As Variant, ByRef dims As Long, ByRef transpose As Boolean, ByRef dest As Variant) As Long

That was working for me...

Best regards,
Roland

basic examples only work with a modification of xlpython.xlam

Hi!

I have just started with xlpython today and I was unable to run this example:

from xlpython import *

@xlfunc
def DoubleSum(x, y):
    '''Returns twice the sum of the two arguments'''
    return 2 * (x + y)

Excel was complaining about the following line:

Sub XLPMacroOptions2010(macroName As String, desc, argdescs() As String)
    Application.MacroOptions macroName, Description:=desc, ArgumentDescriptions:=argdescs
End Sub

I have changed it to:

Sub XLPMacroOptions2010(macroName As String, desc, argdescs() As String)
    Application.MacroOptions macroName, Description:=desc
End Sub

... and now it works.

What is causing this and how can I avoid this situation?

I use Windows 7 and Excel 2007.

Thank you!

Best regards,
Alex

Question

Hi, trying to get this working and having a lot of trouble - could you possibly provide an example of a macro that say, sums the values in a selected range? By calling a python script? I'm having trouble making even a simple program that actually calls a python script and does anything..

some questions (issues?)

Dear Eric,

I have the following problem using the Py instruction as mentioned in your documentation. As you can see in the snapshot (2) when I tried to perform the local evaluation of an expression, I got the error : "Object required". Any hint what should I check ? (as mentioned before, I am using ExcelPyhon 2.0.6).

Point (1) is just a remark about part of the code (check of the 64bit version) is shown as syntax error in the VB IDE.

Thank you again for your help.

image

Problem with XLPMacroOptions2010

Hi Eric,
I was getting an error in this sub when importing UDFS (in Excel 2010), "Method 'MacroOptions' of object '_Application' failed". I tracked it down to a verbose doc string; it looks like desc can only be 255 characters long. I've made the below fix and life is good:

Sub XLPMacroOptions2010(macroName As String, desc, argdescs() As String)
If Len(desc) > 255 Then
    desc = Left$(desc, 255)
End If
    Application.MacroOptions macroName, Description:=desc, ArgumentDescriptions:=argdescs
End Sub

Thanks for the good work,
Eric

Printing List of Tuples to worksheet

hi Eric,

Is there any way for a python function to return a list of tuples and then print that 2-dimensional array to a worksheet without using a VBA UDF.

e.g.

Sub getList(strInput)
Dim cell As Range
Set m = Py.Module("WorkbookName")
Set res = Py.call(m, "getAll", Py.Tuple(Py.Str(strInput))) 'This is a list of tuples
Set cell = ThisWorkbook.Sheets("Output").Cells(1, 1)
cell.Resize(UBound(res, 1), UBound(res, 2)).Value = Application.transpose(res) 'ERROR!
End Sub

I tried doing a Py.Var and Py.Str on the res but this didn't work.

Thanks,

Charlie

Setup error

When I click on the Setup Excel Python Smily I get a window saying "error 1004" in execution time (translation from Spanish). I get two buttons: One to end, and the other to "depurar" which I think it means clean the code and a Visual Basic GUI opens highlighting the following code:

On Error GoTo 0
wb.VBProject.VBComponents.Import wb.Path + Application.PathSeparator + "xlpython" + Application.PathSeparator + "xlpython.bas"

**** which is part of the following code module:

End If
Next f
If Not isVersionOK Then
MsgBox "The installation folder already exists, but it does not contain ExcelPython version " + ver + "." _
+ vbCrLf + vbCrLf + "Installation folder: " + wb.Path + Application.PathSeparator + "xlpython" _
+ vbCrLf + vbCrLf + "To set up a fresh install please delete it and try again. Note that you may need to close Excel to delete it." _
, vbCritical, "Error installing ExcelPython runtime"
Exit Sub
End If
Else
fso.CopyFolder ThisWorkbook.Path + Application.PathSeparator + "xlpython", wb.Path + Application.PathSeparator + "xlpython"
End If

    On Error GoTo not_present
    wb.VBProject.VBComponents.Remove wb.VBProject.VBComponents("xlpython")

not_present:
On Error GoTo 0
wb.VBProject.VBComponents.Import wb.Path + Application.PathSeparator + "xlpython" + Application.PathSeparator + "xlpython.bas"

    ' create skeleton py file
    Set fso = CreateObject("Scripting.FileSystemObject")
    If Not fso.FileExists(wb.Path + Application.PathSeparator + fso.GetBaseName(wb.name) + ".py") Then
        Set f = fso.CreateTextFile(wb.Path + Application.PathSeparator + fso.GetBaseName(wb.name) + ".py", True)
        f.WriteLine "from xlpython import *"
        f.Close
    End If
    'MsgBox "You can now write user-defined functions for this workbook in Python in the file '" + wb.Path + Application.PathSeparator + fso.GetBaseName(wb.Name) + ".py'." + vbCrLf + "Please consult the online docs for more information on how it works.", Title:="ExcelPython setup successful!"
End If

End Sub

Sub XLPMacroOptions2010(macroName As String, desc, argdescs() As String)
Application.MacroOptions macroName, Description:=desc, ArgumentDescriptions:=argdescs
End Sub

Problem upgrading from 2.0.6 to 2.0.8

Hi Eric,
I just tried upgrading using the zip file option and when I try to Import Python UDFs I get an error when it tries to import one of the libraries in my code. I run in a virtualenv and only have that library installed in the virtualenv, not my main Python install. All the libs prior to it are standard Python libs.

I upgraded by overwriting the existing xlpython.xlm with the new one, zipped up the old files in the xlpytion directory, dragged in the new files. Opened xlpython.xlm, ran Setup ExcelPython and clicked on Import Python UDFs and got this error: http://i.imgur.com/lNaIaG2.png

I successfully rolled back by putting back the 2.0.6 xlpython.xlm, restored the files in the xlpython directory and I'm up and running.

This is Win 7, 32 bit Python, 2.7.5.

I tried diffing some of the files between the two releases but there isn't anything obvious to me.

Thanks,
Eric

Import Python UDFs crash if docstring is too big

I was trying to import a python function which had a very large docstring description and the import caused run-time error 1004. I commented out the docstring and the import was fine.

I believe there may be a limit to the docstring size when importing to excel.

Setup Error: Run-time error '76': Path not found

i get this error when i try to setup excelpython. when i open the debugger it points me to this line:

fso.CopyFolder ThisWorkbook.Path + Application.PathSeparator + "xlpython", wb.Path + Application.PathSeparator + "xlpython"

Run-time error '-2147467259 (80004005)':

Hi Eric,

I upgraded my pythonexcel from version 1 to version 2 and likewise updated the code. However, now my program returns the error.

Run-time error '-2147467259 (80004005)':

Automation Error
Unspecified Error

error

code is simple:

Set res = Py.Call(Py.Module("order_dups"), "duplicate_order", _
Args:=Py.Tuple(ActiveSheet.Cells(row, 1).Value))

Any ideas?

Documentation update

In Update Addin01.md, edit:

Next write your user-defined function in Python. In the previous step ExcelPython will have created a file called Book1.py in the same folder as Book1.xlsm in which the Python functions to be used in the workbook can be defined.

to:

must be defined

I've never tried forking a project in GitHub before, I'll give it a shot this week and try to send the change to you.

Taking an input from Excel and passing to Python function

Hi there. First of all, I'm really excited about excelpython, it looks awesome.

I intend to use it to update a web application via its API based on values in a spreadsheet. I've tested this using your example of a macro created in python and assigned to a button in excel.

This works fine, but I've hardcoded my username and password into the python function and I'd like to take these arguments from InputBoxes in Excel.

How would I do this?

Purpose of @xlfunc

I have noticed that if I leave out @xlfunc from the top of the functions in the Python code, everything seems to work the same.

Am I missing something?

Reload True functionality not working(?)

Hi Eric,
I set reload to True in Py.Module and it works for that module:

Sub Test()
Set m = Py.Module("aaaa", True)
Debug.Print Py.Str(Py.Call(m, _
                    "test1", Py.Tuple("param1", "param2)))
End Sub

However, for aaaa, imported modules don't reload automatically. I was putting in debug statements to print to the python window and noticed that when I put them in the imported module, I had to restart Excel to get any output (put the print.... block in db_routines and didn't get any output until I restarted Excel):

import import db_routines

def aaaa(param1, param2):
    results = db_routines.test()

    print '#'*40
    import sys
    print sys._getframe().f_code.co_name
    print conn_db
    print '#'*40
    sys.exit()

I added

Set x = Py.Module("db_routines", True)

to Sub Test() and it started to reload db_routines, however it would be more straightforward to propagate the initial setting to all imported modules if that is possible?

Thanks,
Eric

Consistent naming

Currently there is wide variety of names:

ExcelPython, xlpython, xlpy

The .bas file is called xlpython, the Setup button in the addin talks about an xlpy folder when it really copies xlpython and the module of the add-in is called ExcelPython.

File not found: excelpython27.dll

Hi Eric

i'm having issue with my two pc and they are running same system Win7-64 sp1 wth Office2010 sp2 32bit, it said ""File not found: excelpython27.dll"" when i try to using it.

IIve tried copy excelpython27.dll from SysWOW64 to system32, but it still not work.

any idea?

Not support UTF8 Encoding?

I tried to use ExcelPython in a xlsm file containing Asian Characters, it didn't work.
ExcelPython is a very promising tool for people play with numbers, good job!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.