通过xlwings从excel中使用Gspread启动Python函数
我正试图通过xlwings从excel中使用Gspread启动一个python函数。在上下文中,我这样做是为了能够将数据从google工作表“数据库”导入到我的excel硬拷贝文件中。当我从Python控制台启动该函数时,它工作得非常好,但当我通过使用RunPython的宏从Excel启动它时,它似乎不工作 更准确地说,我添加了标志,以查看问题出在哪里:通过xlwings从excel中使用Gspread启动Python函数,python,xlwings,gspread,Python,Xlwings,Gspread,我正试图通过xlwings从excel中使用Gspread启动一个python函数。在上下文中,我这样做是为了能够将数据从google工作表“数据库”导入到我的excel硬拷贝文件中。当我从Python控制台启动该函数时,它工作得非常好,但当我通过使用RunPython的宏从Excel启动它时,它似乎不工作 更准确地说,我添加了标志,以查看问题出在哪里: def main(): wb = xw.Book.caller() wb.sheets['Dashboard'].range('J3')
def main():
wb = xw.Book.caller()
wb.sheets['Dashboard'].range('J3').value=0#used as a flag
import gspread
from oauth2client.service_account import ServiceAccountCredentials
wb.sheets['Dashboard'].range('J3').value=1.5#used as a flag
# use creds to create a client to interact with the Google Drive API
scope = ['https://spreadsheets.google.com/feeds']
wb.sheets['Dashboard'].range('J3').value=1.6#used as a flag
creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
wb.sheets['Dashboard'].range('J3').value=1.7#used as a flag
client = gspread.authorize(creds)
wb.sheets['Dashboard'].range('J3').value=1#used as a flag
在尝试运行程序后,我在J3单元格中得到的值是1.6,这意味着导致问题的行是:
creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
client_secret.json文件与python脚本和excel文件位于同一工作目录中。如果你有任何关于什么可能是问题的想法,以及我如何解决它,那就太好了
谢谢你的帮助 正如@Felix Zumstein所指定的,解决方案是指定“client_secret”json文件的完整路径,可能使用os.path.dirname(os.path.abspath(file))
RunPython
的工作目录可能会有所不同,您现在还不能在xlwings中设置它,因此,您需要使用json文件的完整路径。这确实是个问题!有没有办法通过RunPython()获取Python脚本的当前工作目录?如果我想分发我的代码,这将很方便…您应该能够在脚本中使用类似于os.path.join(os.path.dir(\uuuu file\uuuu),'file\u name')
的东西。这与:os.path.dirname(os.path.abspath(file))一起使用非常感谢!