遇到2个bug。
1,处理电商订单时,由于订单号过长,导致订单号结尾变成了0000。设置读取数据为str字符串格式即可。
2,当待合并的sheet中有空表时,发现汇总结果为空。因此在第一个表的时候,就生成合并文件。防止汇总错误。
import os
import pandas as pd
import warnings
warnings.filterwarnings("ignore") # 忽略warning消息
dir = r'D:\hebing' # 设置文件夹的路径,方便后面遍历文件夹内的所有表格
DFs = [] # 新建列表,存放每个文件数据框(每一个excel读取后存放在数据框,依次读取多个相同结构的Excel文件并创建DataFrame)
# 将第一个excel的sheet名称保存下来,便于汇总后命名
for root, dirs, files in os.walk(dir):
for file in files:
file_path = os.path.join(root, file) # 测试的文件夹中,没有子文件夹,所以用当前文件夹和文件名组合成一个完整路径
# 将第一个excel的sheet名称保存下来,便于汇总后命名
if file == files[0]:
sheetnames = pd.read_excel(file_path, sheet_name=None).keys()
for this_sheetname in sheetnames:
num = 0
for root2, dirs2, file2s in os.walk(dir):
for file2 in file2s:
file_path2 = os.path.join(root2, file2) # 测试的文件夹中,没有子文件夹,所以用当前文件夹和文件名组合成一个完整路径
#设置默认的格式为dtype=str,防止电商的订单号过长而不能完全显示。
df = pd.read_excel(file_path2, sheet_name=this_sheetname, header=0, dtype=str)
#默认用第一个excel文件的表头生成文件。防止由于sheet为空时,导致合并结果有误差。
if df.empty:
print(file_path2)
if num == 0:
DFs.append(df)
else:
pass
else:
DFs.append(df)
alldata = pd.concat(DFs)
pathssss = os.path.join(os.path.dirname(dir), this_sheetname + '.xlsx')
alldata.to_excel(pathssss, sheet_name=this_sheetname, index=False, engine='openpyxl') # index:表示是否写行索引,默认为True
DFs = []