最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python Tkinter實(shí)現(xiàn)將ZIP中的CSV批量轉(zhuǎn)換為Excel

 更新時(shí)間:2026年01月21日 09:40:39   作者:weixin_46244623  
這篇文章主要為大家詳細(xì)介紹了Python如何結(jié)合Tkinter實(shí)現(xiàn)將ZIP中的CSV批量轉(zhuǎn)換為Excel,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解下

一、需求背景

在日常數(shù)據(jù)處理中,經(jīng)常會(huì)遇到如下場(chǎng)景:

  • CSV 文件被 打包在 ZIP 壓縮包中
  • ZIP 可能 設(shè)置了密碼
  • CSV 文件 編碼不統(tǒng)一(UTF-8 / GBK / GB2312)
  • 希望 批量轉(zhuǎn)換為 Excel(.xlsx)
  • 給普通用戶使用,最好有 圖形界面 + 進(jìn)度條

本文將使用 Python + Tkinter 實(shí)現(xiàn)一個(gè) 桌面工具,完成:

  • 選擇 ZIP 文件
  • 支持輸入 ZIP 密碼
  • 自動(dòng)識(shí)別 CSV 編碼
  • CSV 轉(zhuǎn) Excel(全部轉(zhuǎn)為文本格式)
  • 顯示轉(zhuǎn)換進(jìn)度條

二、功能說(shuō)明

程序主要包含以下模塊:

模塊功能
tkinter圖形界面
zipfile解壓 ZIP
chardetCSV 編碼識(shí)別
pandasCSV 解析
openpyxlExcel 處理
ttk.Progressbar進(jìn)度條

三、完整代碼實(shí)現(xiàn)

直接復(fù)制即可運(yùn)行(Python ≥ 3.8)

import csv
import tkinter as tk
from tkinter.ttk import Progressbar
from tqdm import tqdm
import pandas as pd
import io
import chardet
import openpyxl
import zipfile
from tkinter import simpledialog, filedialog, messagebox
import threading
import tempfile

def has_password(zip_file_path):
    try:
        with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:
        
            for file_name in zip_ref.namelist():
               if zip_ref.getinfo(file_name).flag_bits & 0x1:  # 判斷是否需要密碼
                  return True
               else:
                   return False               
    except RuntimeError:
        return False
def check_password(zip_path, password):
    with zipfile.ZipFile(zip_path, 'r') as zip_ref:
        try:
            zip_ref.setpassword(password.encode('utf-8'))
            return zip_ref.testzip() is None
        except RuntimeError:
            return False
def read_csv_from_zip(zip_path, password):
    output_file = filedialog.asksaveasfilename(filetypes=[('Excel文件', '*.xlsx')])  
    xlsx_file_path = output_file+".xlsx"
    process_button.config(state="disabled")
    process_button.config(text="正在處理中...")
    with zipfile.ZipFile(zip_path, 'r') as zip_ref:
        zip_ref.setpassword(password.encode('utf-8'))
        file_list = zip_ref.namelist()
        for file_name in file_list:
            if zip_ref.getinfo(file_name).flag_bits & 0x1:  # 判斷是否需要密碼
                if not password:
                    messagebox.showerror("錯(cuò)誤", "壓縮文件需要密碼,請(qǐng)輸入密碼")
                    return
            with zip_ref.open(file_name, 'r') as file:
                content = file.read()
               
                # 使用 chardet 自動(dòng)檢測(cè)文件編碼方式
                detected_encoding = chardet.detect(content)['encoding'].lower()
                if detected_encoding == "gb2312":
                    detected_encoding = "gbk"
                else:
                    detected_encoding = detected_encoding
        
                csvreader = io.TextIOWrapper(io.BytesIO(content), encoding=detected_encoding)
                total_rows = sum(1 for row in csvreader)
                #print(total_rows)
                csvreader.seek(0)  # Reset the file pointer to the beginning
                progress_bar.pack()
                progress_label.pack()
                progress_bar["maximum"] = total_rows  # Set the maximum value for progress bar
                #workbook = openpyxl.Workbook()
                #sheet = workbook.active
                data = []  # To store CSV data
                for i, row in enumerate(csvreader):
                    # Replace this with your actual processing logic
                    # For demonstration purposes, we'll just print the rows
                    data.append(row)
                    progress_bar["value"] = i + 1  # Update the progress bar
                    progress_label.config(text=f"Progress: {i+1}/{total_rows}")  # Update progress label
                    root.update_idletasks()  # Force the GUI to update
                    #text_row = [str(cell) for cell in row]
                    #print(text_row)
                    #sheet.append(text_row)    
                #workbook.save(xlsx_file_path)
                df = pd.DataFrame(data, dtype='str')
                output_file = output_file+".xlsx"
                df.to_excel(output_file, index=False)
                #progress_label.pack_forget()    
                #progress_bar.pack_forget()
                #root.update_idletasks() 
                process_button.config(text=f"保存成功")
                #root.update_idletasks() 
                process_button.config(state="normal",text="開(kāi)始處理")
                messagebox.showinfo("保存成功", f"CVS修復(fù)成功:{output_file}")
                #progress_label.pack_forget()  
                #progress_bar.pack_forget()
                root.update_idletasks() 
def browse_zip_file():
    global zip_file_path_entry, password_entry

    file_path = filedialog.askopenfilename(filetypes=[("Zip文件", "*.zip")])
    if file_path:
        zip_file_path_entry.delete(0, tk.END)
        zip_file_path_entry.insert(tk.END, file_path)
def process_files():
    zip_path = zip_file_path_entry.get()
    password = password_entry.get()
    if password and not check_password(zip_path, password):
        messagebox.showerror("錯(cuò)誤", "壓縮文件密碼不正確")
        return  False
    root.update_idletasks()
    try:
        def process_zip():
            try:
                read_csv_from_zip(zip_path, password)
                messagebox.showinfo("Success", "處理完成")
            except Exception as e:
                messagebox.showerror("Error", f"處理失敗: {e}")
        thread = threading.Thread(target=process_zip)
        thread.start()
    except Exception as e:
        status_label.config(text=str(e))
# Create the main application window
root = tk.Tk()
root.title("CSV修復(fù)工具")
root.geometry("650x430")

# Create a button to select the CSV file

# Create the progress bar in determinate mode


# 創(chuàng)建主窗口

# 設(shè)置圖標(biāo)文件路徑
# icon_file = "logo.ico"  # 替換為你的圖標(biāo)文件路徑
# # 更改窗口圖標(biāo)
# root.iconbitmap(icon_file)
# 添加 Logo
logo_image = tk.PhotoImage(file="logo.png")
logo_label = tk.Label(root, image=logo_image)
logo_label.pack(pady=10)
# 創(chuàng)建控件
frame1 = tk.Frame(root)
frame1.pack(pady=10) 

zip_file_path_label = tk.Label(frame1, text="文件路徑:",font=("微軟雅黑", 12))
zip_file_path_label.grid(row=0, column=0)

zip_file_path_entry = tk.Entry(frame1, width=24,font=("微軟雅黑", 12))
zip_file_path_entry.grid(row=0, column=1)

zip_file_path_button = tk.Button(frame1, text="瀏 覽", command=browse_zip_file,font=("微軟雅黑", 12))
zip_file_path_button.grid(row=0, column=2)

frame2 = tk.Frame(root)
frame2.pack()
password_label = tk.Label(frame2, text="解壓密碼:",font=("微軟雅黑", 12))
password_label.grid(row=0, column=0)

password_entry = tk.Entry(frame2, width=30, show='*',font=("微軟雅黑", 12))
password_entry.grid(row=0, column=1)
process_button = tk.Button(root, text="開(kāi)始處理", command=process_files,font=("微軟雅黑", 12))
process_button.pack(pady=10)
progress_bar = Progressbar(root, orient="horizontal", length=300, mode="determinate")
progress_bar.pack(pady=10)
progress_bar.pack_forget()
# Create a label to show progress information
progress_label = tk.Label(root, text="Progress: 0/0",font=("微軟雅黑", 12))
progress_label.pack(pady=5)
progress_label.pack_forget()
status_label = tk.Label(root, text="", fg="red")
status_label.pack()
author_name = "michah"
author_phone = "180xxxxxxxxx"
author_department = "xxxx部門(mén)" 
#author_info_label = tk.Label(root, text=f"開(kāi)發(fā)者姓名:{author_name}\n\n聯(lián)系方式:{author_phone}\n\n所屬部門(mén):{author_department}", font=("Helvetica", 12), justify="left")
#author_info_label.pack(side="bottom", padx=10, pady=10)
copyright_label = tk.Label(root, text="? 2023 michah  All rights reserved.", font=("微軟雅黑", 10))
copyright_label.pack(side="bottom", padx=15, pady=5)
development_date_label = tk.Label(root, text="開(kāi)發(fā)者:michah 手機(jī)號(hào)碼:180xxxxxxxxx 所屬部門(mén):xxxx部門(mén) 版本號(hào):v0.1 開(kāi)發(fā)日期:2023年8月6日", font=("微軟雅黑", 10))
development_date_label.pack(side="bottom", padx=10, pady=5)
# 運(yùn)行主循環(huán)
root.mainloop()

linux字體不全 界面估參考 (windows正常)

四、關(guān)鍵代碼解析

ZIP 加密文件判斷

zip_ref.getinfo(file_name).flag_bits & 0x1
  • flag_bits最低位為 1 表示加密文件
  • 沒(méi)輸入密碼直接拋異常,避免讀取失敗

CSV 編碼自動(dòng)識(shí)別

detected_encoding = chardet.detect(content)['encoding']

并對(duì)常見(jiàn)問(wèn)題做兼容處理:

if detected_encoding == "gb2312":
    detected_encoding = "gbk"

避免 pandas 讀取失敗。

CSV → Excel(全部轉(zhuǎn)文本)

new_sheet.append([str(cell) if cell is not None else "" for cell in row])

防止 Excel 自動(dòng)科學(xué)計(jì)數(shù)

保證身份證 / 銀行卡號(hào)不丟失

進(jìn)度條更新邏輯

progress = int(processed_files / total_files * 100)
progress_var.set(progress)
  • 文件數(shù) 計(jì)算進(jìn)度
  • 簡(jiǎn)單直觀,適合 GUI 場(chǎng)景

五、運(yùn)行效果

程序界面包含:

  • ZIP 密碼輸入框
  • 文件選擇按鈕
  • 實(shí)時(shí)更新的進(jìn)度條

非常適合 內(nèi)部工具 / 運(yùn)維 / 財(cái)務(wù) / 數(shù)據(jù)人員 使用。

到此這篇關(guān)于Python Tkinter實(shí)現(xiàn)將ZIP中的CSV批量轉(zhuǎn)換為Excel的文章就介紹到這了,更多相關(guān)Python CSV轉(zhuǎn)換為Excel內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Python 函數(shù)list&read&seek詳解

    Python 函數(shù)list&read&seek詳解

    這篇文章主要介紹了Python 函數(shù)list&read&seek詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-08-08
  • Python3實(shí)現(xiàn)從排序數(shù)組中刪除重復(fù)項(xiàng)算法分析

    Python3實(shí)現(xiàn)從排序數(shù)組中刪除重復(fù)項(xiàng)算法分析

    這篇文章主要介紹了Python3實(shí)現(xiàn)從排序數(shù)組中刪除重復(fù)項(xiàng)算法,結(jié)合3個(gè)完整實(shí)例形式分析了Python3針對(duì)排序數(shù)組的遍歷、去重、長(zhǎng)度計(jì)算等相關(guān)操作技巧,需要的朋友可以參考下
    2019-04-04
  • Python中的常見(jiàn)數(shù)據(jù)集打亂方法

    Python中的常見(jiàn)數(shù)據(jù)集打亂方法

    這篇文章主要介紹了Python中的常見(jiàn)數(shù)據(jù)集打亂方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-02-02
  • python print輸出延時(shí),讓其立刻輸出的方法

    python print輸出延時(shí),讓其立刻輸出的方法

    今天小編就為大家分享一篇python print輸出延時(shí),讓其立刻輸出的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2019-01-01
  • Python判斷值是否在list或set中的性能對(duì)比分析

    Python判斷值是否在list或set中的性能對(duì)比分析

    這篇文章主要介紹了Python判斷值是否在list或set中的性能對(duì)比分析,結(jié)合實(shí)例形式對(duì)比分析了使用list與set循環(huán)的執(zhí)行效率,需要的朋友可以參考下
    2016-04-04
  • 程序猿新手學(xué)習(xí)必備的Python工具整合

    程序猿新手學(xué)習(xí)必備的Python工具整合

    這篇文章主要介紹了程序猿新手必備的Python工具整合,Python 是一種開(kāi)源編程語(yǔ)言,用于 Web 編程、數(shù)據(jù)科學(xué)、人工智能和許多科學(xué)應(yīng)用
    2021-09-09
  • Python實(shí)現(xiàn)身份證號(hào)碼驗(yàn)證的示例代碼

    Python實(shí)現(xiàn)身份證號(hào)碼驗(yàn)證的示例代碼

    本文主要介紹了Python實(shí)現(xiàn)身份證號(hào)碼驗(yàn)證的示例代碼,當(dāng)用戶輸入身份證號(hào),按下檢查按鈕,即可判斷身份證號(hào)是否正確,具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-02-02
  • Python使用asyncio包處理并發(fā)的實(shí)現(xiàn)代碼

    Python使用asyncio包處理并發(fā)的實(shí)現(xiàn)代碼

    這篇文章主要介紹了Python使用asyncio包處理并發(fā),asyncio包使用事件循環(huán)驅(qū)動(dòng)的協(xié)程實(shí)現(xiàn)并發(fā),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì)對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-12-12
  • jupyter 導(dǎo)入csv文件方式

    jupyter 導(dǎo)入csv文件方式

    這篇文章主要介紹了jupyter 導(dǎo)入csv文件方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-04-04
  • 基于Python實(shí)現(xiàn)天天酷跑功能

    基于Python實(shí)現(xiàn)天天酷跑功能

    這篇文章主要介紹了基于Python實(shí)現(xiàn)天天酷跑功能,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-01-01

最新評(píng)論

丰原市| 邛崃市| 凤庆县| 文安县| 黎平县| 凉山| 绥中县| 洛川县| 观塘区| 枣阳市| 乳源| 舟山市| 措勤县| 调兵山市| 丰顺县| 阜南县| 沈丘县| 石首市| 偃师市| 斗六市| 卓尼县| 讷河市| 司法| 城固县| 十堰市| 尚志市| 阜新市| 威信县| 苍梧县| 肥东县| 宁陕县| 开平市| 陵川县| 宁远县| 梅河口市| 仁布县| 锦州市| 惠州市| 循化| 阿合奇县| 都昌县|