本文档总结了 excelgridconverter.py 脚本所涉及的关键 python 知识点。该脚本用于从多个 excel 文件中提取特定格式的数据并转换为一个新的 excel 文件。
导入库
脚本使用了以下主要库:
tkinter:用于创建图形用户界面。pandas:用于处理 excel 数据。os:用于处理文件和目录路径。
import tkinter as tk from tkinter import filedialog, messagebox import pandas as pd import os
pandas 数据处理
读取 excel 文件
使用 pd.read_excel 方法读取 excel 文件,并使用 sheet_name=none 参数读取所有工作表。添加 index_col=none 参数以确保第一列不会被自动设置为索引列。
source_df = pd.read_excel(file_path, sheet_name=none, index_col=none) source_data = source_df['一格一案']
数据提取
通过 pandas 的 iloc 方法,根据行列索引提取特定数据。
result_data = {
'网格编号': source_data.iloc[1, 1],
'责任段': source_data.iloc[1, 3],
...
}处理合并单元格数据:
risk_check_path = "\n".join(source_data.iloc[9:19, 1].dropna().astype(str)) result_data['五、风险项点检查路径'] = risk_check_path
创建 dataframe 并导出为 excel 文件
将所有提取的数据放入一个 dataframe 中,并使用 to_excel 方法导出为 excel 文件。
result_df = pd.dataframe(all_data) result_df.to_excel(output_file_path, index=false)
tkinter gui 界面
创建主窗口
使用 tk.tk 创建主窗口,并设置窗口标题、大小和位置。
root = tk.tk()
root.title("excel 转换工具")
root.geometry(f'{window_width}x{window_height}+{position_right}+{position_top}')创建按钮和标签
使用 tk.button 和 tk.label 创建按钮和标签,并设置其属性和布局。
title_label = tk.label(root, text="excel 转换工具", font=("arial", 18))
title_label.pack(pady=20)
select_button = tk.button(root, text="选择 excel 文件", command=select_files, font=("arial", 12))
select_button.pack(pady=10)文件操作
文件对话框
使用 filedialog.askopenfilenames 打开文件选择对话框,允许用户选择多个 excel 文件。使用 filedialog.asksaveasfilename 打开文件保存对话框,允许用户选择保存路径。
file_paths = filedialog.askopenfilenames(filetypes=[("excel 文件", "*.xlsx")])
output_file_path = filedialog.asksaveasfilename(defaultextension=".xlsx", filetypes=[("excel 文件", "*.xlsx")])主要函数解释
transform_to_result_format_specific
该函数从源数据中提取特定字段,并返回一个字典格式的结果数据。
def transform_to_result_format_specific(source_data, source_file_path):
risk_check_path = "\n".join(source_data.iloc[9:19, 1].dropna().astype(str))
result_data = { ... }
return result_dataselect_files
该函数处理文件选择、数据转换和结果保存的主要逻辑。
def select_files():
file_paths = filedialog.askopenfilenames(filetypes=[("excel 文件", "*.xlsx")])
all_data = []
for file_path in file_paths:
source_df = pd.read_excel(file_path, sheet_name=none, index_col=none)
source_data = source_df['一格一案']
transformed_data = transform_to_result_format_specific(source_data, file_path)
all_data.append(transformed_data)
result_df = pd.dataframe(all_data)
output_file_path = filedialog.asksaveasfilename(defaultextension=".xlsx", filetypes=[("excel 文件", "*.xlsx")])
if output_file_path:
result_df.to_excel(output_file_path, index=false)
messagebox.showinfo("成功", "文件已成功转换并保存。")总结
通过本脚本,我们学习了如何使用 pandas 读取和处理 excel 数据,如何使用 tkinter 创建图形用户界面,以及如何处理文件对话框和文件操作。这些知识点在日常的 python 开发中非常实用,特别是涉及数据处理和用户界面的项目中。
到此这篇关于python提取特定格式的数据的文章就介绍到这了,更多相关python提取数据内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论