尝试通过tkinter导出带有“保存为”选项的excel文件

6ljaweal  于 2023-04-07  发布在  其他
关注(0)|答案(1)|浏览(135)

正如标题所示,我正在用Python创建一个Excel文件,并试图添加一个“保存为”tkinter函数,该函数将允许用户将导出的Excel文件保存在他们喜欢的地方。(通过输入确切的路径),但是创建“保存为”选项比预期的要困难。(由于明显的原因省略了信息),请让我知道我是否可以提供更多上下文的任何其他信息:

import pandas as pd
import pyodbc
from tkinter import * 
from tkinter import ttk 
from tkinter import filedialog
from tkinter.filedialog import asksaveasfile

root = Tk() 
root.geometry('200x150') 

cnxn = pyodbc.connect('')

script1=""

script2=""

df1 = pd.read_sql_query(script1, cnxn)
df2 = pd.read_sql_query(script2, cnxn)

def save(): 
    
    files = [("Excel files", "*.xlsx"),('All Files', '*.*')] 
    file = asksaveasfile(filetypes = files, defaultextension = files)

    df1.to_excel(file, sheet_name='Initial Appointment', index=False)
    df2.to_excel(file, sheet_name='Follow Ups', index=False)
  
btn = ttk.Button(root, text = 'Save', command = lambda : save()) 
btn.pack(side = TOP, pady = 20) 
  
mainloop()

编辑:“保存为”对话框打开,但它不保存Excel文件,而是脚本,所以它似乎.我可以保存为Excel文件,但当打开它,我得到一个错误,说它是无效的(这可能意味着无论我保存的不是这种格式).

7lrncoxx

7lrncoxx1#

有点晚了,但希望能帮助到其他人。
我遇到了这个问题。我在windows10上使用openpyxl,tkinter,它保存了它,但它没有添加.xlsx扩展名,所以一个快速解决方案是只添加字符串。
我把这段代码贴出来,以防其他人有同样的问题:

**重要提示:**请确保您是通过命令提示符运行脚本,并以管理员身份使用脚本。Openpyxl会向windows写入内容,如果您不是以普通用户身份运行命令提示符,有时它将无法工作。

from tkinter import filedialog
from tkinter import *
import numpy as np
from openpyxl import Workbook
from openpyxl.utils import get_column_letter
from openpyxl.styles import Font, Color, colors, PatternFill
from openpyxl.chart import ScatterChart, Reference, Series

root = Tk()
root.title('Example to save stuff to excel')
root.geometry('600x600')
    
def to_excel():    
    '''
    moving some data to excel or some other program that can open excel files such as open office
    '''
    filename_path =  filedialog.asksaveasfilename(initialdir = 'C:/', title = 'Save file as', filetypes = (('Archivos de excel','*.xls'),('All Files', '*.*')))
    filename_path = filename_path + '.xlsx'
    wb = Workbook()                                                         # Objeto de openpyxl, nos ayuda a crear sheets y el workbook principal
    ws1 = wb.create_sheet('Sheet_A', 0)               
    ws1.title = 'datos'
    x = np.arange(0, 100, 1)
    y = np.arange(0, 400, 4)
    
    # pretty colors to put in your excel file
    yellowFill = PatternFill(start_color = '15D321', end_color = '15D321', fill_type = 'solid')
    greenFill = PatternFill(start_color = 'FFFF99', end_color = 'FFFF99', fill_type = 'solid')

    ws1['A1'].font = Font(bold = True)
    ws1['A1'].fill = greenFill
    ws1['B1'].fill = greenFill
    ws1.cell(row = 1, column = 1).value = 'Ejemplo'
   
    ws1['A10'].font = Font(bold = True)
    ws1['A10'].fill = yellowFill
    ws1['B10'].font = Font(bold = True)
    ws1['B10'].fill = yellowFill
    ws1.cell(row = 10, column = 1).value = 'x'
    ws1.cell(row = 10, column = 2).value = 'y'

    row_j = 11
    for i in range(len(x)):
        ws1.cell(row = row_j, column = 1).value = x[i]
        ws1.cell(row = row_j, column = 2).value = y[i]
        row_j = row_j + 1
    
    wb.save(filename = filename_path)

save_label = Label(root, text = 'Save', padx = 5, pady = 5)
save_label.grid(row = 0, column = 1, padx = 10, pady = 5)

button_save = Button(root, text = 'Click me', padx = 5, pady = 5, command = to_excel)
button_save.grid(row = 2, column = 1)

root.mainloop()

相关问题