简体   繁体   English

无法使用 VBA 执行 Python 以使用 xlwings 创建文件

[英]Can't execute Python with VBA to create a file using xlwings

I would like to run a Python script from Excel.我想从 Excel 运行 Python 脚本。 The Python script has the task to create a file. Python 脚本具有创建文件的任务。 As a help I used the quickstart "Call Python from Excel" as you can see here:作为帮助,我使用了快速入门“从 Excel 调用 Python”,如下所示:

https://docs.xlwings.org/en/stable/quickstart.html https://docs.xlwings.org/en/stable/quickstart.html

However, I don't want Python to write "hello world" to Excel, but instead create a file:但是,我不希望 Python 将“hello world”写入 Excel,而是创建一个文件:

import numpy as np
import xlwings as xw

def world():
    wb = xw.Book.caller()
    wb.sheets[0].range('A1').value = 'Hello World!'

Instead of the code shown above I replaced the lines with:我用以下代码代替了上面显示的代码:

import numpy as np
import xlwings as xw

def world():
    f = open("myfile.txt", "w")

However, no file is created.但是,不会创建任何文件。 I have not found an answer to this problem on my research, so I ask for help here.我在我的研究中没有找到这个问题的答案,所以我在这里寻求帮助。

You need to save the workbook for anything to be created您需要为要创建的任何内容保存工作簿

https://docs.xlwings.org/en/stable/api.html#xlwings.Book.save https://docs.xlwings.org/en/stable/api.html#xlwings.Book.save

In your second example, you're not specifying a full path - The working directory may be different to what you expect.在您的第二个示例中,您没有指定完整路径 - 工作目录可能与您期望的不同。 Instead of "myFile.txt" can you do "c:\\full\\path\\to\\folder\\myFile.txt" (Obviously change the path to suit your environment)而不是“myFile.txt”你可以做“c:\\full\\path\\to\\folder\\myFile.txt”(显然改变路径以适应你的环境)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM