Search code examples
excelnumpyxlwings

Cannot import pandas/numpy into xlwings script


I am trying to call an xlwings python script from within Excel, but I a get an error message as soon as I try to import numpy: Original error was: DLL load failed while importing _multiarray_umath: The specified module could not be found.

Multiple sites suggest that this might be a question of conda not being properly installed, but I cannot figure out how to get it right.

The script I am working with is this. It works without import numpy as np, and as soon as the line is uncommented, I get the above error message.

import xlwings as xw
#import numpy as np
# uncommenting the above line will lead to the error message

def main():
    wb = xw.Book.caller()
    sheet = wb.sheets[0]
    if sheet["A1"].value == "Hello xlwings!":
        sheet["A1"].value = "Bye xlwings!"
    else:
        sheet["A1"].value = "Hello xlwings!"

@xw.func
def add_two(x):
    return x+2

@xw.func
def hello(name):
    return f"Hello {name}!"

if __name__ == "__main__":
    xw.Book("test_project.xlsm").set_mock_caller()
    main()

Just running python in the console works:

(xlwings) PS C:\tools\Anaconda3\envs\xlwings> ./python -i
Python 3.9.7 | packaged by conda-forge | (default, Sep 29 2021, 19:20:16) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pandas as pd
>>> import numpy as np
>>> df = pd.DataFrame({'a': [1,2,3], 'b': [2,3,4]})
>>> print(df)
   a  b
0  1  2
1  2  3
2  3  4
>>> exit()
(xlwings) PS C:\tools\Anaconda3\envs\xlwings>

I installed xlwings in its own environment, versions are:

# packages in environment at C:\tools\Anaconda3\envs\xlwings:
#
# Name                    Version                   Build  Channel
ca-certificates           2021.10.8            h5b45459_0    conda-forge
intel-openmp              2021.4.0          h57928b3_3556    conda-forge
libblas                   3.9.0              12_win64_mkl    conda-forge
libcblas                  3.9.0              12_win64_mkl    conda-forge
liblapack                 3.9.0              12_win64_mkl    conda-forge
mkl                       2021.4.0           h0e2418a_729    conda-forge
numpy                     1.21.2           py39h6635163_0    conda-forge
openssl                   3.0.0                h8ffe710_1    conda-forge
pandas                    1.3.3            py39h2e25243_0    conda-forge
pip                       21.3               pyhd8ed1ab_0    conda-forge
python                    3.9.7           h900ac77_3_cpython    conda-forge
python-dateutil           2.8.2              pyhd8ed1ab_0    conda-forge
python_abi                3.9                      2_cp39    conda-forge
pytz                      2021.3             pyhd8ed1ab_0    conda-forge
pywin32                   301              py39hb82d6ee_0    conda-forge
setuptools                58.2.0           py39hcbf5309_0    conda-forge
six                       1.16.0             pyh6c4a22f_0    conda-forge
sqlite                    3.36.0               h8ffe710_2    conda-forge
tbb                       2021.3.0             h2d74725_0    conda-forge
tzdata                    2021c                he74cb21_0    conda-forge
ucrt                      10.0.20348.0         h57928b3_0    conda-forge
vc                        14.2                 hb210afc_5    conda-forge
vs2015_runtime            14.29.30037          h902a5da_5    conda-forge
wheel                     0.37.0             pyhd8ed1ab_1    conda-forge
xlwings                   0.24.9           py39hcbf5309_0    conda-forge

The xlwings config parameters are (sheet xlwings.conf):

Interpreter_Win C:\tools\Anaconda3\envs\xlwings\python.exe
Interpreter_Mac 
PYTHONPATH  
Conda Path  C:\tools\Anaconda3
Conda Env   xlwings
UDF Modules 
Debug UDFs  FALSE
Use UDF Server  FALSE
Show Console    TRUE

And the full error message is here:

---------------------------
Error
---------------------------
Original error was: DLL load failed while importing _multiarray_umath: The specified module could not be found.
Please carefully study the documentation linked above for further help.
and make sure that they are the versions you expect.
  * The NumPy version is: "1.20.3"
  * The Python version is: Python3.8 from "C:\tools\Anaconda3\python.exe"
Please note and check the following:
    https://numpy.org/devdocs/user/troubleshooting-importerror.html
We have compiled some common reasons and troubleshooting tips at:
installed.
many reasons, often due to issues with your setup or how NumPy was
Importing the numpy C-extensions failed. This error can happen for
IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!
ImportError: 
    raise ImportError(msg)
  File "C:\tools\Anaconda3\lib\site-packages\numpy\core\__init__.py", line 48, in <module>
    from . import core
  File "C:\tools\Anaconda3\lib\site-packages\numpy\__init__.py", line 145, in <module>
    import numpy as np
  File "c:\users\tobia\onedrive\documents\python scripts\excelpython\test_project\test_project.py", line 2, in <module>
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "<frozen importlib._bootstrap_external>", line 843, in exec_module
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
    return _bootstrap._gcd_import(name[level:], package, level)
  File "C:\tools\Anaconda3\lib\importlib\__init__.py", line 127, in import_module
    module = import_module(module_name)
  File "C:\tools\Anaconda3\lib\site-packages\xlwings\udfs.py", line 404, in get_udf_module
    module = get_udf_module(module_name, xl_workbook)
  File "C:\tools\Anaconda3\lib\site-packages\xlwings\udfs.py", line 660, in import_udfs
    return ToVariant(getattr(obj, method)(*pargs, **kwargs))
  File "C:\tools\Anaconda3\lib\site-packages\xlwings\server.py", line 194, in Call
    return func(*args)
  File "C:\tools\Anaconda3\lib\site-packages\win32com\server\policy.py", line 586, in _invokeex_
    return S_OK, -1, self._invokeex_(dispid, lcid, wFlags, args, None, None)
  File "C:\tools\Anaconda3\lib\site-packages\win32com\server\policy.py", line 283, in _invoke_
    return self._invoke_(dispid, lcid, wFlags, args)
  File "C:\tools\Anaconda3\lib\site-packages\win32com\server\policy.py", line 278, in _Invoke_ -2147467259

Press Ctrl+C to copy this message to the clipboard.
---------------------------
OK   
---------------------------

Thanks for helping out!


Solution

  • I think I could resolve the problem by not relying on paths to the interpreter, but rather conda and environment:

    Basically I only needed to change the sheet "xlwings.conf" to:

    Interpreter_Win 
    Interpreter_Mac 
    PYTHONPATH  
    Conda Path      C:\tools\Anaconda3
    Conda Env       xlwings
    UDF Modules 
    Debug UDFs      FALSE
    Use UDF Server  FALSE
    Show Console    FALSE
    

    (or the equivalent in Excels xlwings menu). This is the link that explained things: https://docs.xlwings.org/en/latest/addin.html#user-settings - "If you use conda envs on Windows, then leave this empty and use Conda Path and Conda Env below instead."