""" 时间:2019-12-17 功能:合并文件夹下多个excel文件 注意事项:xlrd和xlwt处理的是xls文件,单个sheet最大行数是65535,如果有更大需要的,建议使用openpyxl函数,最大行数达到1048576。 """ import io import sys #改变标准输出的默认编码 #utf-8中文乱码 sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='gb18030') import openpyxl from openpyxl import load_workbook import os from openpyxl import Workbook from openpyxl.drawing.image import Image # 注意当你想往excel写入图片时,可使用这个方法。 def del_excel(): # file_list = os.walk('D:/集合/银行/') # 获取这个文件夹下所有的excel文档。 file_list = os.walk('C:\\Users\\Administrator\\Desktop\\ceshi\\') # 获取这个文件夹下所有的excel文档。 for file in file_list: path_list = file[2] wb = Workbook() ws1 = wb.create_sheet('合并', index=0) # 创造合并之后的sheet表的名字 title_list = ["分类ID","产品属性","Parent SKU","产品标题","产品描述","sku","变种名称","变种属性名称一","变种属性名称二", "变种属性值一","变种属性值二","价格","促销价","折扣活动ID","库存","重量","主图(URL)地址","附图1", "附图2","附图3","附图4","附图5","附图6","附图7","附图8地址","变种图","长(cm)","宽(cm)","高(cm)", "发货期","来源URL","尺码图","产品id","销量","浏览","收藏"] # sheet表的表头创建 ws1.append(title_list) for ph in path_list: # 迭代遍历所有excel 文档 print('ph %s' % ph) ph = ph.replace('~$', '') if str(ph).endswith('sx'): # res = find_excel(path='D:/集合/银行/' + ph) # 构建单个文档路径 res = find_excel(path='C:\\Users\\Administrator\\Desktop\\ceshi\\' + ph) # 构建单个文档路径 wb2 = load_workbook('C:\\Users\\Administrator\\Desktop\\ceshi\\' + ph) sheet = wb2.active for index, row in enumerate(sheet.rows): if index > 0: # 因为 index = 0时,获取到的为表格的值。 # print("####", row) c = [] for item in row: # 这个迭代无特殊情况 可简化一下 print("++++", item.value) c.append(item.value) # 注意,获取到的是一行的值 # print("=====", c) # print("*****", c) # return c ws1.append(c) print("----->", res) # ws1.append(res) wb.save('C:\\Users\\Administrator\\Desktop\\ceshi\\result.xlsx') def find_excel(path): # 获取excel文档内容的方法 wb = load_workbook(path) sheet = wb.active c = [] # content = [] for index, row in enumerate(sheet.rows): if index > 0: # 因为 index = 0时,获取到的为表格的值。 # print("####", row) for item in row: # 这个迭代无特殊情况 可简化一下 # print("++++", item.value) c.append(item.value) # 注意,获取到的是一行的值 # print("=====", c.append(item.value)) # print("*****", c) # return c # print("!!!!!!!!!!", c) return c # return content if __name__ == '__main__': del_excel() print("执行结束")