【问题标题】:How do I save to a specific directory using openpyxl?如何使用 openpyxl 保存到特定目录?
【发布时间】:2020-10-06 11:36:58
【问题描述】:

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

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

wb.save(save_spot)

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

def set_save_destination():
    global save_spot
    save_spot = filedialog.askdirectory()
    save_spot = str(save_spot)

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

monthly_browse = ttk.Button(self, text='Select Save Destination', command=set_save_destination)

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

【问题讨论】:

  • 这能回答你的问题吗? filedialog-tkinter-and-opening-files
  • 为什么不用filedialog.asksaveasfilename() 而不是filedialog.askdirectory()
  • 这里你不需要使用global,事实上你可能永远不需要使用它。

标签: python python-3.x tkinter openpyxl


【解决方案1】:

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

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

所以你可以在 save_spot 变量中添加额外的文件名

    save_spot = str(save_spot)+'/filename.xlsx'

【讨论】:

  • 非常感谢!我没有意识到您必须在路径末尾添加文件名
  • 不客气,有时很容易搞砸,但幸运的是 python 是动态类型语言,所以很容易修复代码 :)
  • 请不要忘记将答案标记为正确,提前谢谢!
猜你喜欢
  • 1970-01-01
  • 2015-10-04
  • 2020-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多