Calling a UDF through Excel
Testing with the following UDF, I found that no matter where the Excel and Python files were saved (even when in different directories from one another), the output returned was the "C:\Users\username\Documents" directory:
import os
import xlwings as xw
@xw.func
def cwd():
wb = xw.Book.caller()
x = os.getcwd()
return x
Running the function outside of Excel/xlwings:
However, if you are running the python script itself outside of Excel/xlwings through Excel, then it will depend on where you are running the script from.
Using the below code (similar to yours), then the output to cell A1 will change by where I run the code from.
# python script saved in "C:\Users\username\Desktop"
import os
import xlwings as xw
file = r'C:\Users\username\Book1.xlsm'
ws = xw.Book(file).sheets("Sheet1")
ws.range("A1").value = os.getcwd()
- By just opening the file in file explorer (thus running the script), the directory is the folder that the Python script is saved in (in this case the Desktop).
- By opening the cmd and starting in a different directory, then running
python "C:\Users\username\Desktop\pythonscript.py"
the output to Excel is the current working directory in the cmd.
See the answers to this question for a more in-depth answer.
" Okay, and **what happened** when you tried it? Did a path show up in the expected cell of the spreadsheet? Is that path like what you expect? **why did this test not answer the question**?
– Karl Knechtel Jan 25 '23 at 22:19