Python | 選擇文件將csv轉成xlsx

# -*- coding: utf-8 -*-
"""
Created on Wed Feb 23 08:49:49 2022
@author: 02279074
function:
     convert CSV to XLSX
"""
import os
from tkinter import Tk,Label
from tkinter import filedialog
import pandas as pd

#check whether is CSV file
def isValidFile(obj):
    typeList=(".csv",".CSV")
    if obj.endswith(typeList):
        return True

#revise file name
def ChangeFileType(obj):
    if len(obj)>0:
        portion=os.path.splitext(obj)
        newObj=portion[0]+".xlsx"
        return newObj

root=Tk()                           #initial dialogue
root.title("ELANCO")
# root.withdraw()                   #hiden tkinter.TK()

filePath=filedialog.askopenfilename(title="Select.CSV.File")

if len(filePath)==0:
    #add warning
    lb=Label(root,text="no.csv.file.be.selected",
             height=3,width=20,
             fg="Blue",relief="solid",
             font="Times 20 bold")
    lb.pack()                       #must, for pack in root frame
    root.mainloop()
elif isValidFile(filePath):
    df=pd.read_csv(filePath,parse_dates=True)
    outputFile=ChangeFileType(filePath)
    df.to_excel(outputFile,index=False)
    root.destroy()
else:
    root.destroy()                  #close Tk screen
#exit Tk screen to release memory
try:
    root.quit()
except:
    pass
input('Input Enter Key')   #stay screen in EXE

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章