如何使用 openpyxl 保存到特定目录?

0 python tkinter python-3.x openpyxl

我正在尝试将使用 openpyxl 创建的 Excel 工作簿保存到用户通过 Tkinter“浏览”按钮输入的特定目录。我将工作簿保存在输入的“保存点”处,但收到一条错误消息,指出它是一个目录。

在生成工作簿的函数中,我有:

wb.save(save_spot)
Run Code Online (Sandbox Code Playgroud)

“保存点”是通过函数生成的:

def set_save_destination():
    global save_spot
    save_spot = filedialog.askdirectory()
    save_spot = str(save_spot)
Run Code Online (Sandbox Code Playgroud)

用户可以在我的 GUI 类中通过以​​下 Tkinter GUI 代码选择目录:

monthly_browse = ttk.Button(self, text='Select Save Destination', command=set_save_destination)
Run Code Online (Sandbox Code Playgroud)

我收到的错误消息是“IsADirectoryError”,但我不确定问题是什么,因为它说您可以直接将目录输入到保存方法中。我是编程新手,完全自学,所以任何帮助都会很棒!谢谢你!

小智 6

您需要提供所需文件夹的完整路径,请参阅下面的示例

from openpyxl import Workbook
wb = Workbook()
ws1 = wb.active
ws1.title = "1st Hour"
wb.save('/home/user/Desktop/FileName.xlsx')
Run Code Online (Sandbox Code Playgroud)

因此您可以另外将文件名添加到 save_spot 变量中

    save_spot = str(save_spot)+'/filename.xlsx'
Run Code Online (Sandbox Code Playgroud)