赞
踩
表一的sheet1:
表一的sheet2:
表二:
合并结果:
使用列表存储文件名
allxls是等待合并的两个文件
将合并的内容放入endxls中
- # 使用列表存储所有的文件名
- allxls = ["F:/test1.xlsx", "F:/test2.xlsx"]
- endxls = "F:/test3.xlsx"
打开excle文件
- def open_xls(file):
- try:
- # 打开excle文件,获取工作簿对象
- workbook = openpyxl.load_workbook(file)
- return workbook
- except Exception as er:
- print("打开出错,错误为:" + er)
从工作簿中获取表单对象
- # 从工作簿中获取表单对象 ['信1601-1', '信1601-2']
- def get_sheet(workbook):
- sheet = workbook.sheetnames
- return sheet
完整代码
- # 使用openpyxl包,可以进行修改,文件原内容不变
- import openpyxl
-
- # 使用列表存储所有的文件名
- allxls = ["F:/考研复试准备/数据挖掘自学/test1.xlsx", "F:/考研复试准备/数据挖掘自学/test2.xlsx"]
- endxls = "F:/考研复试准备/数据挖掘自学/test3.xlsx"
-
-
- def open_xls(file):
- try:
- # 打开excle文件,获取工作簿对象
- workbook = openpyxl.load_workbook(file)
- return workbook
- except Exception as er:
- print("打开出错,错误为:" + er)
-
-
- # 从工作簿中获取表单对象 ['信1601-1', '信1601-2']
- def get_sheet(workbook):
- sheet = workbook.sheetnames
- return sheet
-
- cellvalue = [] #使用一个list存储读取到的数据
- fnum = 0 #sheet表单个数
- rnum = 0 #总行数
- workbook1 = open_xls(allxls[0]) #打开文件test1
- workbook2 = open_xls(allxls[1]) #打开文件test2
- workbook3 = open_xls(endxls) #打开文件test3
- sheets1 = get_sheet(workbook1) #获得表单名
- sheets2 = get_sheet(workbook2) #获得表单名
- # 获取每个单元格的值
-
- for sheet_num in sheets1:
- # 按顺序获取某个表单
- sheet = workbook1[sheets1[fnum]]
- fnum += 1
- for row in sheet.rows:
- rnum += 1
- for cell in row:
- cellvalue.append(cell.value)
-
- for sheet_num in sheets2:
- sheet = workbook2[sheets2[fnum]]
- fnum += 1
- for row in sheet.rows:
- rnum += 1
- for cell in row:
- cellvalue.append(cell.value)
-
-
- sheet = workbook3.active
- count = 0
-
- for j in range(0, rnum):
- for k in range(0, 3):
- sheet.cell(row=j + 1, column=k + 1).value = cellvalue[j * 3 + k]
- workbook3.save('test3.xlsx')
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。