Python3.5 处理excel_2(有续表的情况下怎样合并)
望共同进步
转载请注明地址:
有关xlrd,xlwt模块的处理在前面已经写了相关简单操作,请查看 http://blog.csdn.net/weixin_39701039
这里直接上代码了:
#coding:utf-8 import xlrd import xlwt import re path = r'G:\任务20180312' data = xlrd.open_workbook(path + '/' + 'test2.xlsx') sh_nums = len(data.sheets()) print(sh_nums) n_Lists = [] for i in range(sh_nums): sheet = data.sheets()[i] name = sheet.name #print(name) #print(type(name)) n_Lists.append(name) #获取工作表的名称list print(n_Lists) workbook = xlwt.Workbook('ascii') #初始化工作表名称前缀 n_prefix0 = '' n_sheet = 0 sheet_name = '' for i in n_Lists: #定义正则 p = r'([0-9].+?)[\u4e00-\u9fa5]' pattern = re.compile(p) n_prefix = re.findall(pattern,i)[0] n_prefixs = re.split('-',n_prefix) #得到工作表名称前缀,以辨别哪些是能合在一起的续表 n_prefix = n_prefixs[0] print(n_prefix) #以名称索引打开列表 sheet1 = data.sheet_by_name(i) nrows = sheet1.nrows nclos = sheet1.ncols if n_prefix == n_prefix0: print('yes') #如果前缀相同,判断为续表,望下继续写数据,工作表名称不变,不新建工作表 x1 = x1 print(x1) sheet_name = sheet_name else: #前缀不同,工作表名称改变, sheet_name = i #即新建一工作表 worksheet = workbook.add_sheet(sheet_name) x1 = 0 pass for x in range(nrows): for y in range(nclos): worksheet.write(x1, y, sheet1.cell(x, y).value) #写入数据,行+1连续 x1 = x1 + 1 print(sheet_name) print(nrows) #返回上一级工作表名称前缀 n_prefix0 = n_prefix print(n_prefix0) workbook.save(path + '/' + 'test2.xls' )
图1(合并前):
图2(合并后):
望有所帮助,望采纳!