用python编写的excel拆分小工具

from datetime import date,datetime

from openpyxl import Workbook

from openpyxl import load_workbook

from openpyxl.styles import Border, Side, Font,Alignment

from tkinter import *

from tkinter import filedialog

from tkinter import messagebox

‘‘‘

设置单元格样式

‘‘‘

‘‘‘

def set_style(name,height,bold=False):

style = xlwt.XFStyle() # 初始化样式

font = xlwt.Font() # 为样式创建字体

font.name = name # ‘Times New Roman‘

font.bold = bold

font.color_index = 4

font.height = height

style.font = font

# style.borders = borders

return style

‘‘‘

‘‘‘

def create_file(rows,nrows,ncols,filename):

f = xlwt.Workbook()                  #创建工作簿

sheet1 = f.add_sheet(u‘sheet1‘,cell_overwrite_ok=True) #创建第一个sheet:

for i in range(0,nrows):

for m in range(0,ncols):

sheet1.write(i,m,rows[i][m],set_style("楷体",300,bold=False))#write(行索引,列列索引,要写入的值,字体)

sheet1.col(m).width = 0x0d00 + m*2500  #设置行宽度

f.save(filename+‘.xls‘)

‘‘‘

‘‘‘

border = Border(left=Side(border_style=None,color=‘FF000000‘),\

right=Side(border_style=None,color=‘FF000000‘),\

top=Side(border_style=None,color=‘FF000000‘),\

bottom=Side(border_style=None,color=‘FF000000‘),\

diagonal=Side(border_style=None,color=‘FF000000‘),\

diagonal_direction=10,outline=Side(border_style=None,color=‘FF000000‘),\

vertical=Side(border_style=None,color=‘FF000000‘),\

horizontal=Side(border_style=None,color=‘FF000000‘))

alignment=Alignment(horizontal=‘general‘,vertical=‘bottom‘,\

text_rotation=0,wrap_text=False,shrink_to_fit=False,indent=0)

‘‘‘

font = Font(name=‘楷体‘,size=15,bold=False,italic=False,\

vertAlign=None,underline=‘none‘,strike=False,color=‘FF000000‘)

def create_file(rows,nrows,ncols,filename):

f = Workbook()                  #创建工作簿

sheet = f.active #创建第一个sheet:

for i in range(1,nrows+1):

for m in range(1,ncols+1):

#write(行索引,列列索引,要写入的值,字体)

sheet.cell(row = i,column = m,value = rows[i-1][m-1]).font = font

#sheet.cell(row = i,column = m).border = border

#sheet.cell(row = i,column = m).alignment = alignment

#sheet1.col(m).width = 0x0d00 + m*2500  #设置行宽度

#下一句为改变列宽的方法,还是从国外网站找的,非常有用

sheet.column_dimensions[sheet.cell(row = i,column = m).column].width = 30

f.save(filename_save+filename+‘.xlsx‘)

def create_list(list_name):

list_name = []

return list_name

def main(filepath,col_str):

#workbook = xlrd.open_workbook(filepath)

wb = load_workbook(filename = filepath,data_only = True)#不读取公式

sheetnames = wb.get_sheet_names()

sheet = wb.get_sheet_by_name(sheetnames[0])

nrows = sheet.max_row

ncols = sheet.max_column

#print(nrows)

#sheet = workbook.sheet_by_index(0) # sheet索引从0开始

‘‘‘

# 获取所有sheet

#print(workbook.sheet_names()) # [u‘sheet1‘, u‘sheet2‘]

#sheet2_name = workbook.sheet_names()[1]

# 根据sheet索引或者名称获取sheet内容

#sheet2 = workbook.sheet_by_name(‘sheet2‘)

# sheet的名称,行数,列数

#print(sheet.name,sheet.nrows,sheet.ncols,type(sheet.nrows))

# 获取整行和整列的值(数组)

‘‘‘

rows = []

col_num = 0

row_num = 0

for i in range(1,nrows+1):

list_temp = []

for m in range(1,ncols+1):

data = sheet.cell(row=i,column=m).value

#print(type(data))

#获取划分条件所在的列数,作为main函数的参数传入

if data == col_str:

col_num = m

row_num = i

if (type(data) == datetime):

#转换日期,更加方便,无需datemode打开

data = data.strftime(‘%Y/%m/%d‘)

list_temp.append(data) #循环获取表格的所有内容

rows.append(list_temp)

#cols = sheet.col_values(2) # 获取第三列内容

#print(rows)

list_name = []

for i in range(1,nrows+1):

list_name.append(str(sheet.cell(row = i,column = col_num).value))

list_name.append("None")

list_name_unique = list(set(list_name))

list_name_unique.remove(col_str)

list_name_unique.remove("None")#目的是去除空值,这里空值显示为None

for m in list_name_unique:

list_num = [rows[row_num-1]]#col_num为逻辑序号,需要做-1处理

for i in range(0,nrows):

if m == rows[i][col_num-1]:

list_num.append(rows[i])

create_file(list_num,len(list_num),ncols,m)

messagebox.showinfo(‘提示框‘,‘拆分成功‘,default = ‘ok‘)

root = Tk()

def choosefile():

filename_file = filedialog.askopenfilename()

global filename_save

filename_save = filename_file.rsplit(sep = ‘/‘,maxsplit = 1)[0]+‘/‘

e_file.delete(0,END)

e_file.insert(0,filename_file)

#判断拆分按钮是否可用

def checkButton1(a):

if a.strip() == ""or v2.get().strip() == "":

bton2[‘state‘] = DISABLED

return True

else:

bton2[‘state‘] = NORMAL

return True

def checkButton2(a):

if a.strip() == ""or v1.get().strip() == "":

bton2[‘state‘] = DISABLED

return True

else:

bton2[‘state‘] = NORMAL

return True

Label(root,text = "文件").grid(row = 0)

Label(root,text = "字段").grid(row = 1)

bton1 = Button(root,text = "选择文件",width = 10,command = choosefile)

bton1.grid(row = 3,column = 0,sticky = W,padx = 10,pady = 5)

bton2 = Button(root,text = "开始拆分",state = DISABLED,width = 10,command = lambda:main(e_file.get(),e_name.get()))

bton2.grid(row = 3,column = 1,sticky = E,padx = 10,pady = 5)

checkButtonCMD1 = root.register(checkButton1)

checkButtonCMD2 = root.register(checkButton2)

v1 = StringVar()

v2 = StringVar()

e_file = Entry(root,textvariable = v1,validate = "key",validatecommand = (checkButtonCMD1,‘%P‘))

e_name = Entry(root,textvariable = v2,validate = "key",validatecommand = (checkButtonCMD2,‘%P‘))

e_file.grid(row = 0,column = 1,padx = 10,pady = 5)

e_name.grid(row = 1,column = 1,padx = 10,pady = 5)

mainloop()

from datetime import date,datetime

from openpyxl import Workbook

from openpyxl import load_workbook

from openpyxl.styles import Border, Side, Font,Alignment

from tkinter import *

from tkinter import filedialog

from tkinter import messagebox

‘‘‘

设置单元格样式

‘‘‘

‘‘‘

def set_style(name,height,bold=False):

style = xlwt.XFStyle() # 初始化样式

font = xlwt.Font() # 为样式创建字体

font.name = name # ‘Times New Roman‘

font.bold = bold

font.color_index = 4

font.height = height

style.font = font

# style.borders = borders

return style

‘‘‘

‘‘‘

def create_file(rows,nrows,ncols,filename):

f = xlwt.Workbook()                  #创建工作簿

sheet1 = f.add_sheet(u‘sheet1‘,cell_overwrite_ok=True) #创建第一个sheet:

for i in range(0,nrows):

for m in range(0,ncols):

sheet1.write(i,m,rows[i][m],set_style("楷体",300,bold=False))#write(行索引,列列索引,要写入的值,字体)

sheet1.col(m).width = 0x0d00 + m*2500  #设置行宽度

f.save(filename+‘.xls‘)

‘‘‘

‘‘‘

border = Border(left=Side(border_style=None,color=‘FF000000‘),\

right=Side(border_style=None,color=‘FF000000‘),\

top=Side(border_style=None,color=‘FF000000‘),\

bottom=Side(border_style=None,color=‘FF000000‘),\

diagonal=Side(border_style=None,color=‘FF000000‘),\

diagonal_direction=10,outline=Side(border_style=None,color=‘FF000000‘),\

vertical=Side(border_style=None,color=‘FF000000‘),\

horizontal=Side(border_style=None,color=‘FF000000‘))

alignment=Alignment(horizontal=‘general‘,vertical=‘bottom‘,\

text_rotation=0,wrap_text=False,shrink_to_fit=False,indent=0)

‘‘‘

font = Font(name=‘楷体‘,size=15,bold=False,italic=False,\

vertAlign=None,underline=‘none‘,strike=False,color=‘FF000000‘)

def create_file(rows,nrows,ncols,filename):

f = Workbook()                  #创建工作簿

sheet = f.active #创建第一个sheet:

for i in range(1,nrows+1):

for m in range(1,ncols+1):

#write(行索引,列列索引,要写入的值,字体)

sheet.cell(row = i,column = m,value = rows[i-1][m-1]).font = font

#sheet.cell(row = i,column = m).border = border

#sheet.cell(row = i,column = m).alignment = alignment

#sheet1.col(m).width = 0x0d00 + m*2500  #设置行宽度

#下一句为改变列宽的方法,还是从国外网站找的,非常有用

sheet.column_dimensions[sheet.cell(row = i,column = m).column].width = 30

f.save(filename_save+filename+‘.xlsx‘)

def create_list(list_name):

list_name = []

return list_name

def main(filepath,col_str):

#workbook = xlrd.open_workbook(filepath)

wb = load_workbook(filename = filepath,data_only = True)#不读取公式

sheetnames = wb.get_sheet_names()

sheet = wb.get_sheet_by_name(sheetnames[0])

nrows = sheet.max_row

ncols = sheet.max_column

#print(nrows)

#sheet = workbook.sheet_by_index(0) # sheet索引从0开始

‘‘‘

# 获取所有sheet

#print(workbook.sheet_names()) # [u‘sheet1‘, u‘sheet2‘]

#sheet2_name = workbook.sheet_names()[1]

# 根据sheet索引或者名称获取sheet内容

#sheet2 = workbook.sheet_by_name(‘sheet2‘)

# sheet的名称,行数,列数

#print(sheet.name,sheet.nrows,sheet.ncols,type(sheet.nrows))

# 获取整行和整列的值(数组)

‘‘‘

rows = []

col_num = 0

row_num = 0

for i in range(1,nrows+1):

list_temp = []

for m in range(1,ncols+1):

data = sheet.cell(row=i,column=m).value

#print(type(data))

#获取划分条件所在的列数,作为main函数的参数传入

if data == col_str:

col_num = m

row_num = i

if (type(data) == datetime):

#转换日期,更加方便,无需datemode打开

data = data.strftime(‘%Y/%m/%d‘)

list_temp.append(data) #循环获取表格的所有内容

rows.append(list_temp)

#cols = sheet.col_values(2) # 获取第三列内容

#print(rows)

list_name = []

for i in range(1,nrows+1):

list_name.append(str(sheet.cell(row = i,column = col_num).value))

list_name.append("None")

list_name_unique = list(set(list_name))

list_name_unique.remove(col_str)

list_name_unique.remove("None")#目的是去除空值,这里空值显示为None

for m in list_name_unique:

list_num = [rows[row_num-1]]#col_num为逻辑序号,需要做-1处理

for i in range(0,nrows):

if m == rows[i][col_num-1]:

list_num.append(rows[i])

create_file(list_num,len(list_num),ncols,m)

messagebox.showinfo(‘提示框‘,‘拆分成功‘,default = ‘ok‘)

root = Tk()

def choosefile():

filename_file = filedialog.askopenfilename()

global filename_save

filename_save = filename_file.rsplit(sep = ‘/‘,maxsplit = 1)[0]+‘/‘

e_file.delete(0,END)

e_file.insert(0,filename_file)

#判断拆分按钮是否可用

def checkButton1(a):

if a.strip() == ""or v2.get().strip() == "":

bton2[‘state‘] = DISABLED

return True

else:

bton2[‘state‘] = NORMAL

return True

def checkButton2(a):

if a.strip() == ""or v1.get().strip() == "":

bton2[‘state‘] = DISABLED

return True

else:

bton2[‘state‘] = NORMAL

return True

Label(root,text = "文件").grid(row = 0)

Label(root,text = "字段").grid(row = 1)

bton1 = Button(root,text = "选择文件",width = 10,command = choosefile)

bton1.grid(row = 3,column = 0,sticky = W,padx = 10,pady = 5)

bton2 = Button(root,text = "开始拆分",state = DISABLED,width = 10,command = lambda:main(e_file.get(),e_name.get()))

bton2.grid(row = 3,column = 1,sticky = E,padx = 10,pady = 5)

checkButtonCMD1 = root.register(checkButton1)

checkButtonCMD2 = root.register(checkButton2)

v1 = StringVar()

v2 = StringVar()

e_file = Entry(root,textvariable = v1,validate = "key",validatecommand = (checkButtonCMD1,‘%P‘))

e_name = Entry(root,textvariable = v2,validate = "key",validatecommand = (checkButtonCMD2,‘%P‘))

e_file.grid(row = 0,column = 1,padx = 10,pady = 5)

e_name.grid(row = 1,column = 1,padx = 10,pady = 5)

mainloop()

时间: 2024-10-10 02:17:41

用python编写的excel拆分小工具的相关文章

用python编写一个高效搜索代码工具

用python编写一个高效搜索代码工具大多码农在linux环境下使用grep+关键词的命令搜索自己想要的代码或者log文件.今天介绍用python如何编写一个更强大的搜索工具,windows下也适用.我们的需求:1, 可以同时指定多个关键词.比如某个文件某一行中有"error: aa bb cc",如果检索关键词error和cc则可以显示该行,避免单一关键词冗余信息太多2, 可以排除某些关键词.对于"error: aa bb cc" ,如果设定排除bb,则不予显示该

Python - 开发截图识别OCR小工具

一.简介 你一定用过那种“OCR神器”,可以把图片中的文字提取出来,极大的提高工作效率. 今天,我们就来做一款实时截图识别的小工具.顾名思义,运行程序时,可以实时把你截出来的图片中的文字识别出来. 二.模块 import keyboard # 用于监控键盘按下,触发事件(pip install keyboard) import time from aip import AipOcr # 调用百度接口(pip install baidu-aip) from PIL import ImageGrab

用python编写的定向arp欺骗工具

刚学习了scapy模块的一些用法,非常强大,为了练手,利用此模块编写了一个arp欺骗工具,其核心是构造arp欺骗包.加了一个-a参数用于进行全网欺骗,先暂不实现.代码如下: 1 #--*--coding=utf-8--*-- 2 3 from scapy.all import * 4 import optparse 5 import threading 6 7 #解决在linux系统上运行时报的unicode编码相关错误 8 import sys 9 reload(sys) 10 sys.set

Python学习之旅:用Python制作一个打字训练小工具

一.写在前面 说道程序员,你会想到什么呢?有人认为程序员象征着高薪,有人认为程序员都是死肥宅,还有人想到的则是996和 ICU. 别人眼中的程序员:飞快的敲击键盘.酷炫的切换屏幕.各种看不懂的字符代码. 然而现实中的程序员呢?对于很多程序员来说,没有百度和 Google 解决不了的问题,也没有 ctrl + c 和 ctrl + v 实现不了的功能. 那么身为一个程序员,要怎么让自己看起来更加“专业”呢?答案就是加快自己的打字速度了,敲的代码可能是错的,但这个13却是必须装的! 然而还是有不少人

Python写的大小写转换小工具

几行代码的小工具,用于进行如下转换 TRANSACTIONS ON CLOUD COMPUTING => Transactions On Cloud Computing orig = 'TRANSACTIONS ON CLOUD COMPUTING' splited = orig.split(' ') handled = '' for word in splited: word = word[0] + word[1:].lower() handled += (' ' + word) handle

Python编写微信打飞机小游戏(四)

之前的工作已经基本上将我方飞机的图形显示工作做的差不多了,这篇博客中我们将开始添加敌方飞机——小型敌机.中型敌机(直升机)和大型敌机(坦克).新建一个enemy.py文件,导入pygame和random模块,开始编写吧(还是要注意文件编码问题,以后就不再啰嗦了). 敌方飞机类与我方飞机模块有一定的相似性,但不会左右移动,不会发射子弹等等.小型敌机是敌方飞机中最基本的类型,一击毙命,没有血量.没有出场音效.中型敌机有一定血量,损毁时附带特殊音效.大型敌机血量最多,出场和损毁时都有特殊音效,游戏中中

Python编写微信打飞机小游戏(一)

最近开始学习Python语言,发现Python有一个神奇的Pygame模块,在编写小游戏时显得非常方便,于是参照教学视频编写了一个微信打飞机的小游戏,网上有很多相关的博客,但都不是很详细,大都是直接贴代码,于是决定沉下心来把编写程序的过程记录下来,与大家分享. 首先声明一点,这篇博客完全参照了小甲鱼的<零基础入门学习Python>教学视频,为了尊重原创,特将原作者的视频地址公布如下:<零基础入门学习Python> Python编译器和Pygame模块的安装网上的教程很多,这里不再赘

用 pyqt4 编写的一个翻译小工具

有时候我们在开发时遇到一些陌生的英文单词或者不容易看出某些长句的中文意思时该怎么办呢?打开桌面上的翻译软件?打开浏览器里收藏着的翻译网址或者直接贴上百度的搜索框去查?这些方法固然可以,还很常见,但如果是 linux 系统的话,很难找到像 windows 上那些公司级别来开发的成熟的翻译软件,所以只能打开浏览器来查了.浏览器一般都会装上一些翻译插件,比如我常用的 chrome 的 划词翻译,直接用这些插件来进行翻译比起打开一个翻译网站或者百度google搜索要更快,毕竟因为加载的内容更少,但这终究

python抓取网站URL小工具

1.安装Python requests模块(通过pip): 环境搭建好了! 2.测试一下抓取URL的过程: 抓取出来的URL有JavaScript代码,正则上还有待更加完善,有兴趣的可以研究下~! 工具源代码: #coding:utf-8 import sys import re import requests #获取输入URL,并获取网页text input = raw_input("please input URL format like this(http://www.baidu.com)