用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()