繁体   English   中英

python-如何让这个变量从我得到的路径中读取 excel 文件?

[英]python- how to make this variable read excel file from the path i get?

我有两个按钮“浏览文件 2A”和“浏览文件 PR”,它们打开并读取选定的 excel 文件路径,我如何才能读取该文件路径(“打开”那些 excel 文件,以便我的 rest 中的代码save_slogan() 有效)通过变量 df1 和 df2? 请参阅我的 function save_slogan(),这里是我的代码:

from tkinter import *

# import filedialog module
from tkinter import filedialog
import pandas as pd
# Function for opening the
# file explorer window
from tkinter import *
import smtplib
def browseFiles1():
    filename = filedialog.askopenfilename(initialdir = "/",
                                          title = "Select a File",
                                          filetypes = (("Text files",
                                                        "*.txt*"),
                                                       ("all files",
                                                        "*.*")))

    # Change label contents
    label_file_explorer.configure(text="File Opened: "+filename)



def browseFiles():
    filename = filedialog.askopenfilename(initialdir = "/",
                                          title = "Select a File",
                                          filetypes = (("Text files",
                                                        "*.txt*"),
                                                       ("all files",
                                                        "*.*")))

    # Change label contents
    label_file_explorer.configure(text="File Opened: "+filename)


def save_slogan():
 import pandas as pd
df1=#read and open the excel file from its file path from function browseFiles() 
df2=#read and open the excel file from its file path from function browseFiles1()
xx1=df1.rename(columns={"Description":"Desc 2A","Doc Number":"Document Number"})
xx=df2.rename(columns={"Description":"Desc PR","Doc Number":"Document Number"})
combined = pd.merge(xx1, xx, how="outer", on="Document Number")
def case_code(row): 
    if row["Tax Amount 2A"] == row["Tax Amount PR"]:
        return "exact"
    elif pd.isna(row["Tax Amount 2A"]):
        return "Addition in PR"
    elif pd.isna(row["Tax Amount PR"]):
        return "Addition in 2A"
    elif row["Tax Amount 2A"] != row["Tax Amount PR"]:
        return "mismatch"

codes=combined.apply(case_code, axis="columns")
answer = combined.assign(**{"Match type": codes})
final=answer[["Match type"] + [*combined.columns]] 
final.to_excel('done1.xlsx')     


# Create the root window
window = Tk()

# Set window title
window.title('File Explorer')

# Set window size
window.geometry("500x500")

#Set window background color
window.config(background = "white")

# Create a File Explorer label
label_file_explorer = Label(window,
                            text = "PR2A",
                            width = 100, height = 4,
                            fg = "blue")


button_explore = Button(window,
                        text = "Browse File 2A",
                        command = browseFiles)
button_explore1 = Button(window,
                        text = "Browse File PR",
                        command = browseFiles1)
button_explore2 = Button(window,
                        text = "Go and Save",
                        command = save_slogan)




# the widgets at respective positions
# in a table like structure by
# specifying rows and columns
label_file_explorer.grid(column = 1, row = 1)

button_explore.grid(column = 1, row = 2)
button_explore1.grid(column=1, row=3)
button_explore2.grid(column=1,row=4)



# Let the window wait for any events
window.mainloop()

请帮忙

您需要存储选定的文件。 由于需要知道选择的文件是“2A”还是“PR”,建议使用字典来存储选择的文件。

您可以将两个browseFiles函数合二为一,并将所需的文件类型作为参数传递:

# dictionary to store the selected files
selected_files = {"2A": None, "PR": None}

def browseFile(ftype):
    filename = filedialog.askopenfilename(initialdir = "/",
                                          title = "Select a File",
                                          filetypes = (("Excel files",
                                                        "*.xlsx"),
                                                       ("all files",
                                                        "*.*")))
    if filename:
        # a file is selected, so store the selected file
        selected_files[ftype] = filename
        # Change label contents
        txt = "\n".join(f"{ftype}: {fname}" for ftype, fname in selected_files.items())
        label_file_explorer.configure(text="File Opened:\n"+txt)

def save_slogan():
    import pandas as pd
    # check whether required files are selected
    if all(selected_files.values()):
        df1=pd.read_excel(selected_files["2A"])
        df2=pd.read_excel(selected_files["PR"])
        xx1=df1.rename(columns={"Description":"Desc 2A","Doc Number":"Document Number"})
        xx=df2.rename(columns={"Description":"Desc PR","Doc Number":"Document Number"})
        combined = pd.merge(xx1, xx, how="outer", on="Document Number")

        def case_code(row):
            if row["Tax Amount 2A"] == row["Tax Amount PR"]:
                return "exact"
            elif pd.isna(row["Tax Amount 2A"]):
                return "Addition in PR"
            elif pd.isna(row["Tax Amount PR"]):
                return "Addition in 2A"
            elif row["Tax Amount 2A"] != row["Tax Amount PR"]:
                return "mismatch"

        codes=combined.apply(case_code, axis="columns")
        answer = combined.assign(**{"Match type": codes})
        final=answer[["Match type"] + [*combined.columns]]
        final.to_excel('done1.xlsx')

然后更改两个按钮的command选项,如下所示:

button_explore = Button(window,
                        text = "Browse File 2A",
                        command = lambda: browseFile("2A"))
button_explore1 = Button(window,
                        text = "Browse File PR",
                        command = lambda: browseFile("PR"))

暂无
暂无

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

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