首页 > 其他分享 >记录一个批量拆分数据粘贴到各个表里的小脚本

记录一个批量拆分数据粘贴到各个表里的小脚本

时间:2024-05-22 22:18:21浏览次数:11  
标签:sheet 表里 win 拆分 cbox ori col 粘贴 sub

import os
import tkinter as tk
import tkinter.filedialog
from tkinter import ttk
import tkinter.messagebox
from tkinter import scrolledtext
import xlwings as xw
from pandas import ExcelFile
from pandas import read_excel

global df_total,cbox_sheet_ori,cbox_col_ori,t1
global files,cbox_sheet_aim,dir_paste


# 粘贴用函数
def paste(excel, sheet, df, start_cell):
    app = xw.App(visible=False, add_book=False)
    # 不弹出提示窗
    app.display_alerts = False
    # 打开工作簿工作表
    load_wb = app.books.open(excel)
    load_ws = load_wb.sheets[f"{sheet}"]
    # #清除sheet内的所有数据
    # load_ws.clear()

    # 将dataframe转成列表写入
    load_ws.range(f'{start_cell}').value = df.values
    # 保存并关闭工作簿
    load_wb.save()
    load_wb.close()
    # 关闭进程
    app.quit()


# 批量刷数
def batch_copy():
    global cbox_sheet_ori,t1
    file_total = tkinter.filedialog.askopenfilename()
    sub_win = tk.Tk()
    sub_win.geometry('270x350')
    sub_win.resizable(height=False, width=False)
    sub_win.title("请输入参数")
    t1 = scrolledtext.ScrolledText(sub_win, width=25,height=15)
    t1.grid(column=1, row=7)
    # ————————————————————————————————————————————————————————————————————
    # 创建组件
    l1 = tk.Label(sub_win, text="选择数据源");cbox_sheet_ori = ttk.Combobox(sub_win, width=20)
    l2 = tk.Label(sub_win, text="选择拆分列");cbox_col_ori = ttk.Combobox(sub_win, width=20)
    l3 = tk.Label(sub_win, text="选择目标");cbox_sheet_aim = ttk.Combobox(sub_win, width=20)
    l4 = tk.Label(sub_win, text="粘贴开始行");t4 = tk.Entry(sub_win, width=25)
    t4.insert(tk.INSERT, "A1")
    sub_win.update()

    # ————————————————————————————————————————————————————————————————————
    # 下拉框选择目标excel
    cbox_sheet_ori = ttk.Combobox(sub_win, width=20)
    df_total_name = ExcelFile(file_total)
    df_total_name = df_total_name.sheet_names
    cbox_sheet_ori['values'] = df_total_name
    cbox_sheet_ori['state'] = 'readonly'
    sub_win.update()

    # 用获取的表名获取全部列名/选取sheet_ori/获取目标df  df_total(不是str的格式
    def appear(*args):
        global df_total,cbox_sheet_ori,cbox_col_ori
        sheet_ori = cbox_sheet_ori.get()
        sub_win.update()
        # print(sheet_ori)
        df_total = read_excel(file_total, sheet_name=sheet_ori)
        columns = df_total.columns.values.tolist()
        sub_win.update()
        # print(columns)
        cbox_col_ori = ttk.Combobox(sub_win, width=20)
        cbox_col_ori['values'] = columns
        cbox_col_ori['state'] = 'readonly'
        cbox_col_ori.grid(column=1, row=2)
        # 选择列名后选择粘贴文件
        cbox_col_ori.bind('<<ComboboxSelected>>', choose_file)
        sub_win.update()
        return
    # 选择表单后选择列名
    cbox_sheet_ori.bind('<<ComboboxSelected>>', appear)
    sub_win.update()

    # ————————————————————————————————————————————————————————————————————
    # 选择目标文件,以此获取粘贴的所有文件目录(files)和粘贴表单(sheet_paste)
    def choose_file(*args):
        global files,cbox_sheet_aim,dir_paste
        notice = tkinter.messagebox.showinfo(title='信息提示!', message='选择批量粘贴对象(用于获取路径和用于粘贴的表单)')
        path_paste = tkinter.filedialog.askopenfilename()
        sheet_name = ExcelFile(path_paste)
        sheet_names = sheet_name.sheet_names
        cbox_sheet_aim = ttk.Combobox(sub_win, width=20)
        cbox_sheet_aim['values'] = sheet_names
        cbox_sheet_aim['state'] = 'readonly'
        cbox_sheet_aim.grid(column=1, row=3)
        # 读取父目录
        dir_paste = os.path.dirname(path_paste)
        files = os.listdir(dir_paste)
        sub_win.update()
        # print(files)
        return

    # ————————————————————————————————————————————————————————————————————
    # 组件位置
    l1.grid(column=0, row=1);cbox_sheet_ori.grid(column=1, row=1)
    l2.grid(column=0, row=2);cbox_col_ori.grid(column=1, row=2)
    l3.grid(column=0, row=3);cbox_sheet_aim.grid(column=1, row=3)
    l4.grid(column=0, row=4);t4.grid(column=1, row=4)

    def get_close():
        # 已读取的目标sheet df文件
        sub_win.update()
        global df_total, cbox_sheet_ori, cbox_col_ori
        global files, cbox_sheet_aim,t1,dir_paste
        sheet_ori = cbox_sheet_ori.get()
        col_aim = cbox_col_ori.get()
        sheet_paste = cbox_sheet_aim.get()
        location = t4.get()
        # sub_win.destroy()
        # print("选择数据源:"+sheet_ori, "选择拆分列:"+col_aim, "选择目标:"+sheet_paste,"起始单元格"+location)
        for i, value in df_total.groupby(col_aim):  ##########失败
            name_1 = value[col_aim].tolist()[0]
            try:
                file = [x for x in files if name_1 in x][0]
                file_path = os.path.join(dir_paste, file)
                try:
                    paste(file_path,sheet_paste,value,location)
                    res = name_1 + "-数据贴入已完成" + "\n"
                except:
                    res = name_1 + "-粘贴失败" + "\n"
            except:
                res = name_1 + "-文件不存在" + "\n"
            t1.insert(tk.END,res)
            sub_win.update()
            t1.see(tk.END)
        t1.insert(tk.END,"运行结束")
        sub_win.update()
        t1.see(tk.END)

    b1 = tk.Button(sub_win, text="执行批量粘贴", command=get_close, width=15)
    b1.grid(column=1, row=6)
    sub_win.mainloop()


batch_copy()

"""
tips:
global控件的内容,最后一起获取,避免重复变量名
使用bind的方法讲选择行为和子函数绑定减少cmd数量 eg:cbox_col_ori.bind('<<ComboboxSelected>>', choose_file)
"""

标签:sheet,表里,win,拆分,cbox,ori,col,粘贴,sub
From: https://www.cnblogs.com/AZ26/p/18207260

相关文章

  • FI凭证拆分
    因为BUZEI只有3位,所以FI凭证限制了最大只能有999行项目。项目背景:有个采购预制了发票之后,不愿意拆分发票(将一张发票分成几张发票)。场景一、收款发票过账场景二、物料移动(超出999)场景三、付款发票过账最开始预计的方案:一.开发程序,将预制的发票,拆分成多张预制发票(最大249行一......
  • Python教程:拆分多级目录的方法
    实现多级目录差分,举例说明如下:假设现有的目录结构如下:1、2、2.1、2.2、2.3、2.4、3、4、5、6、6.1、6.1.1、6.1.2、6.1.3、6.1.4、6.2、6.3、6.4、7、8、9、10。经过差分后,得到的各级目录为:一级目录:1、2、3、4、5、6、7、8、9、10二级目录:2.1、2.2、2.3、2.4和6.1、6.2、6......
  • 139. 单词拆分
    给你一个字符串s和一个字符串列表wordDict作为字典。如果可以利用字典中出现的一个或多个单词拼接出s则返回true。注意:不要求字典中出现的单词全部都使用,并且字典中的单词可以重复使用。示例1:输入:s="leetcode",wordDict=["leet","code"]输出:true解释:返回......
  • vue复制粘贴功能
    第一种【推荐】npminstallclipboard--save<template><div><inputtype="text"v-model="copyText"/><button@click="copyToClipboard">复制到剪贴板</button></div></template><......
  • Linux 中 awk一句某一列来拆分数目
      001、直接拆分[root@PC1test2]#lsoutcome.map[root@PC1test2]#catoutcome.map##准备一个测试文件,依据第一列来拆分文件1snp10559101snp20852041snp301229482snp40......
  • AD中如何使用特殊粘贴和阵列粘贴
    在使用Altiumdesigned(以下简称AD)时,有时需要粘贴元器件。与常用的软件不同,AD的复制粘贴并不是ctrl+C和ctrl+V,并且复制过来的器件并没有保存原先的网络标号,因此需要了解特殊粘贴。板子敷铜之前一般需要放置一些接地的过孔,以这个过孔为例讲一下AD的粘贴操作。选中需要粘贴的器......
  • R:OTU根据分类级别拆分
    输入文件输出文件rm(list=ls())setwd("C:\\Users\\Administrator\\Desktop\\microtable")#设置工作目录library(dplyr)library(tidyr)library(readr)#读取文件data<-readLines('1.txt')#定义分类等级的前缀和列名prefixes<-c("k__","......
  • 对象属性值按长度拆分扩展一个新集合
    packagecom.xx.xx.core.utils;importcn.hutool.core.util.ReflectUtil;importcom.xx.tools.utils.BeanUtil;importcom.xx.tools.utils.StringUtil;importlombok.AllArgsConstructor;importlombok.Data;importlombok.NoArgsConstructor;importlombok.experimen......
  • VirtualBox虚拟机与主机之间双向复制粘贴
    ref:https://learnku.com/articles/68553VirtualBox虚拟机与主机之间双向复制粘贴VM:VirtualBoxv7主机:Win10VMOS:Ubuntu22确保虚拟机系统没有运行,然后在虚拟机软件VirtualBox选择对应设置的虚拟机系统,然后右侧点击设置(Settings)。依次点击常规(General)–>高......
  • 41天【代码随想录算法训练营34期】第九章 动态规划part03 (● 343. 整数拆分 ● 96.
    343.整数拆分classSolution:defintegerBreak(self,n:int)->int:dp=[0]*(n+1)dp[2]=1foriinrange(3,n+1):forjinrange(1,i//2+1):dp[i]=max(dp[i],(i-j)*j,dp[i-j]*j)......