python - xlwings 调用一个应该创建文件的 python 函数,但没有创建文件

标签 python excel xlwings

def create_file():
    file_writer= open('testFile.txt','w')
    file_writer.write('TESTING...;\n')
    file_writer.flush()
    file_writer.close()

def my_macro():
    wb = Workbook.caller()  # Creates a reference to the calling Excel file
    Range('Sheet1', 'C3').value = random.randint(0,10)
    updateValue = Range('Sheet1', 'C3').value
    print("updatedValue=" , updateValue);
    create_file()

if __name__ == '__main__':
    path = os.path.abspath(os.path.join(os.path.dirname(__file__), 'FirstExcel.xlsm'))
    Workbook.set_mock_caller(path)
    my_macro()

当我在 Eclipse 中运行上述代码时,它会创建一个文件并更新 Excel 电子表格。但是,当我从 Excel 运行它时,它会更新电子表格,但不会创建文件。

最佳答案

问题在于,Excel 目前在与从 Python 调用文件时不同的工作目录中启动 Python 解释器。这是 GitHub 上的一个开放问题,请参阅 here .

同时,只需对 open 中的所有文件使用绝对/完整路径和write 。您还应该能够使用类似 os.path.abspath(os.path.join(os.path.dirname(__file__), 'testFile.txt')) 的内容

关于python - xlwings 调用一个应该创建文件的 python 函数,但没有创建文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31840145/

相关文章:

python - 如何根据 PEP8 使用 % 参数格式化此字符串

python - Pandas DataFrame 到 Hive 表

C# 将 csv 转换为 xls(使用现有的 csv 文件)

python - wb = xlwings.Workbook() 在 Mac 上失败

python - 在 Excel 工作表中查找填充内容的范围

python - 运行 xlwings 和 win32com.client 时出错

python - 将 Mat 参数从 Python 传递给 C++ 方法

python - 如何防止 moto 测试抛出 NoSuchBucket 错误?

python - 在 python 中向 csv 数据添加新行

excel - SendInput VB 基本示例