使用Python轻松实现CSV转XLSX转换工具

### 标题:使用Python轻松实现CSV转XLSX转换工具

#### 引言
在数据处理和分析的日常工作中,我们常常需要将CSV(逗号分隔值)文件转换为Excel的XLSX格式以便于进一步的数据操作、可视化或共享。虽然有许多现成的软件可以完成这项任务,但使用Python编写一个自定义的CSV转XLSX转换工具不仅简单快捷,而且具有极大的灵活性和可扩展性。本文将探讨使用Python实现这一过程的优点及其带来的方便。

软件操作界面截图

使用Python轻松实现CSV转XLSX转换工具

下载地址:

https://wwtg.lanzouo.com/iSBiN2m3bt3g
密码:ggbf

#### Python实现CSV转XLSX的优点

1. **灵活性**:
– 使用Python进行编程,可以根据需求定制转换过程。例如,可以轻松添加逻辑来处理特定的数据清洗任务,如去除重复行、填充缺失值等。

2. **集成能力**:
– Python拥有丰富的库支持,如`pandas`和`openpyxl`,使得CSV到XLSX的转换变得异常简单。这些库不仅提供了强劲的功能来读取和写入不同格式的数据文件,还允许与数据库、网络服务等其他数据源无缝集成。

#### 实际应用中的方便之处

– **快速部署**:只需几行代码,就能创建一个有效的CSV转XLSX转换器,超级适合需要快速解决方案的场景。
– **易修改性**:随着需求的变化,很容易调整代码以适应新的要求或改善现有流程。
– **成本效益高**:相比于购买专门的软件,利用Python开发自己的工具几乎没有成本,除了时间和精力之外。

#### 结语
通过Python实现从CSV到XLSX的转换工具,不仅能提供一种高效、灵活且经济的方式来处理数据文件,还能作为学习和掌握Python编程技能的一个实际项目。无论是对于初学者还是有经验的开发者来说,这都是一个值得尝试的任务。希望这篇文章能够激发你动手实践的兴趣,并协助你在日常工作中更有效地管理数据。

源码如下:有需要的可以自行学习 0_0 ~

import pandas as pd
import os
from datetime import datetime
import tkinter as tk
from tkinter import filedialog, messagebox

class FileConverterGUI:
    def __init__(self):
        self.window = tk.Tk()
        self.window.title("CSV批量转XLSX工具")
        self.window.geometry("800x500")
        
        # 输入文件列表框
        self.input_frame = tk.Frame(self.window)
        self.input_frame.pack(pady=20, padx=20, fill=tk.BOTH, expand=True)
        
        self.input_label = tk.Label(self.input_frame, text="选择的文件:")
        self.input_label.pack(anchor='w')
        
        # 创建列表框和滚动条
        self.list_frame = tk.Frame(self.input_frame)
        self.list_frame.pack(fill=tk.BOTH, expand=True)
        
        self.scrollbar = tk.Scrollbar(self.list_frame)
        self.scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        self.files_listbox = tk.Listbox(self.list_frame, width=80, height=10)
        self.files_listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        
        self.files_listbox.config(yscrollcommand=self.scrollbar.set)
        self.scrollbar.config(command=self.files_listbox.yview)
        
        # 按钮框
        self.button_frame = tk.Frame(self.window)
        self.button_frame.pack(pady=10)
        
        self.input_button = tk.Button(self.button_frame, text="选择文件", command=self.select_files)
        self.input_button.pack(side=tk.LEFT, padx=5)
        
        self.clear_button = tk.Button(self.button_frame, text="清空列表", command=self.clear_files)
        self.clear_button.pack(side=tk.LEFT, padx=5)

        # 输出目录
        self.output_frame = tk.Frame(self.window)
        self.output_frame.pack(pady=20)
        self.output_label = tk.Label(self.output_frame, text="输出目录:")
        self.output_label.pack(side=tk.LEFT)
        self.output_path = tk.StringVar()
        self.output_entry = tk.Entry(self.output_frame, textvariable=self.output_path, width=50)
        self.output_entry.pack(side=tk.LEFT, padx=5)
        self.output_button = tk.Button(self.output_frame, text="浏览", command=self.select_output)
        self.output_button.pack(side=tk.LEFT)

        # 转换按钮
        self.convert_button = tk.Button(self.window, text="开始转换", command=self.convert_files)
        self.convert_button.pack(pady=20)

        # 存储文件路径列表
        self.file_paths = []

    def select_files(self):
        files = filedialog.askopenfilenames(
            title='选择CSV文件',
            filetypes=[('CSV文件', '*.csv')]
        )
        if files:
            for file in files:
                if file not in self.file_paths:
                    self.file_paths.append(file)
                    self.files_listbox.insert(tk.END, os.path.basename(file))
            # 默认设置输出目录为第一个文件所在目录
            if not self.output_path.get() and self.file_paths:
                self.output_path.set(os.path.dirname(self.file_paths[0]))

    def clear_files(self):
        self.files_listbox.delete(0, tk.END)
        self.file_paths = []

    def select_output(self):
        dir_path = filedialog.askdirectory(title='选择输出目录')
        if dir_path:
            self.output_path.set(dir_path)

    def convert_single_file(self, input_file, output_dir):
        try:
            # 尝试使用不同的编码方式读取CSV文件
            df = None
            success_encoding = None
            
            encodings = ['gbk', 'gb18030', 'utf-8', 'utf-8-sig', 'big5', 'cp936', 'iso-8859-1', 'latin1']

            for encoding in encodings:
                try:
                    with open(input_file, 'r', encoding=encoding) as f:
                        f.read()
                    df = pd.read_csv(input_file, encoding=encoding, on_bad_lines='skip')
                    success_encoding = encoding
                    break
                except UnicodeDecodeError:
                    continue
                except Exception:
                    continue

            if df is None:
                try:
                    df = pd.read_csv(input_file, encoding='cp437', on_bad_lines='skip')
                    success_encoding = 'cp437'
                except Exception as e:
                    return False, f"无法识别文件编码:{str(e)}"

            if df.empty:
                return False, "CSV文件没有任何数据"

            # 生成输出文件名
            file_name = os.path.splitext(os.path.basename(input_file))[0]
            timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
            output_file = os.path.join(output_dir, f'{file_name}_已成功转换_{timestamp}.xlsx')

            df.to_excel(output_file, index=False, engine='openpyxl')
            return True, success_encoding

        except Exception as e:
            return False, str(e)

    def convert_files(self):
        if not self.file_paths:
            messagebox.showerror("错误", "请先选择要转换的文件!")
            return

        output_dir = self.output_path.get()
        if not output_dir:
            messagebox.showerror("错误", "请选择输出目录!")
            return

        if not os.path.exists(output_dir):
            messagebox.showerror("错误", "输出目录不存在!")
            return

        success_count = 0
        error_files = []

        for file_path in self.file_paths:
            success, message = self.convert_single_file(file_path, output_dir)
            if success:
                success_count += 1
            else:
                error_files.append(f"{os.path.basename(file_path)}: {message}")

        # 显示转换结果
        result_message = f"转换完成!
成功:{success_count}/{len(self.file_paths)}"
        if error_files:
            result_message += "

转换失败的文件:"
            for error in error_files:
                result_message += f"
{error}"
        
        if success_count > 0:
            result_message += f"

文件保存在:{output_dir}"

        if success_count == len(self.file_paths):
            messagebox.showinfo("成功", result_message)
        else:
            messagebox.showwarning("部分成功", result_message)

    def run(self):
        self.window.mainloop()

if __name__ == "__main__":
    app = FileConverterGUI()
    app.run()
© 版权声明
THE END
如果内容对您有所帮助,就支持一下吧!
点赞0 分享
评论 共21条

请登录后发表评论