Implementation of Python merging Excel table of and sheet

  • 2021-10-16 02:22:39
  • OfStack

Using xlrd module and xlwt module

Problem-solving idea: xlwt module is a non-additional write. xls module, so it is necessary to write once with the help of for loop and list, so there is no statement of additional and non-additional.
And merging Excel tables, Treat each Excel table as a row, That is, line merge, for another idea, the labels in Excel table can be regarded as columns, and column merge can be carried out, that is, different labels composed of the same labels in different files can be merged, the same labels in different files can be merged first, and the same labels in different files can form a list, and then the contents of all Excel files can be obtained by merging the different labels composed before.

The source code is as follows:


#导入xlrd和xlwt模块
#xlrd模块是读取.xls的Excel文件的模块,xlwt模块是以非追加的方式写.xls的Excel文件的模块
import xlrd,xlwt
#导入要读的文件的路径
a=["C:/Users/Desktop/m1.xls","C:/Users/Desktop/m2.xls"]
#定义要写的文件的路径
b="C:/Users/Desktop/m3.xls"
#定义函数,判断打开文件是否会发生异常
def open(fileaddress):
  try:
#通过xlrd模块的open_workbook()方法,打开1个Excel文件,定义变量fo为文件句柄
    fo=xlrd.open_workbook(fileaddress)
    return fo
  except Exception as e:
    print("error!"+str(e))
#定义函数,得到某1个Excel文件下某1个标签的行数
def getrows(fo,num):
  table=fo.sheets()[num]
#sheets()函数为xlrd模块自带函数,能以列表的形式返回该Excel文件的标签
  n=table.nrows
#nrows为xlrd模块自带函数,通过某1个标签调用,可得到该标签的行数
  return n
"""
定义函数,可通过Excel文件路径和标签的序列编号得到
任意Excel文件任意标签的内容,且以列表的形式返回
"""
def getsheetcontents(fileaddress,num):
  avalue=[]
  fo=open(fileaddress)
  table=fo.sheets()[num]
  n=table.nrows
  for i in range(0,n):
    """
    row_values()函数为xlrd模块自带函数,通过某1个标签调用,
    可得到该标签的行数据,且这些行数据以列表形式返回,标签中
    1列为1个列表的元素
    """
    rdate=table.row_values(i)
    avalue.append(rdate)
  return avalue
svalue=[]
k=[]
#通过for循环得到所有Excel文件的标签数,且以列表的形式返回
for i in a:
  fo=open(i)
  k.append(len(fo.sheets()))
#对这些标签数进行升序排序
k.sort()
#通过for循环把这些Excel文件中不同标签的所有内容放在列表svalue中
for i in range(0,k[len(k)-1]):
#通过for循环把不同Excel文件的同1个标签放在列表bvalue中
  bvalue=[]
  for j in a:
    print("正在读取"+str(j)+"的第"+str(i)+"个标签")
    bvalue.append(getsheetcontents(j,i))
  svalue.append(bvalue)
#svalue里面就是所有Excel文件的内容

#通过xlwt模块的Workbook()创建1个.xls文件,定义1个变量fw为文件句柄
fw=xlwt.Workbook()
line=0
#add_sheet()函数为xlwt模块自带函数,可得到1个自定义标签
#定义变量ws为标签句柄
ws=fw.add_sheet("sheet1")
"""
通过for循环遍历svalue列表,把最终得到的
某个标签某个文件某行某列的数据写入新标签中
"""
for i in range(0,len(svalue)):
  for j in range(0,len(svalue[i])):
    for m in range(0,len(svalue[i][j])):
      for n in range(0,len(svalue[i][j][m])):
        ws.write(line,n,svalue[i][j][m][n])
#通过line可得到不断增加的行数
      line+=1
print("合并完成")
#save()函数为xlwt自带函数,将合并好的Excel文件保存到某个路径下
fw.save(b)
#xlrd模块和xlwt模块都没有close()函数,即用这两个模块打开文件不用关闭文件

Related articles: