举例:
excel 1:5条数据
excel 2:9条数据
excel 3:4条数据。
正常情况应该是:
合并完后,一个excel,一个sheet,共有18条数据
我的情况是:
合并完后,一个excel,一个sheet,只有excel 1中的5条+excel 2 中的第6条至第9条,
(excel 2中的前5条数据没有,和 excel 3 中的四条数据没有。)
# coding = utf-8
import os
import xlrd
import xlwt
from tqdm import tqdm
file_dir = r"C:\Users\Administrator\Desktop\2018年".replace('\\','/')
os.chdir(file_dir)
workbook_write = xlwt.Workbook(encoding="utf-8")
worksheet = workbook_write.add_sheet("MySheet")
def hebing_excels(file, start_line_num):
workbook_read = xlrd.open_workbook(file)
table = workbook_read.sheet_by_index(0)
for rownum in tqdm(range(table.nrows)):
row_value = [ str(elem).replace(' ','') for elem in table.row_values(rownum) ]
try:
if "姓名" in row_value: #判断是否标题行
row_value.insert(0, "文件名")
for colnum in range(len(row_value)):
worksheet.write(start_line_num, colnum, row_value[colnum])
elif isinstance(int(row_value[0]), int):
row_value.insert(0, file.replace('.xlsx',''))
for colnum in range(len(row_value)):
worksheet.write(start_line_num, colnum, row_value[colnum])
else:
pass
except:
pass
start_line_num = start_line_num +1
for file in os.listdir(file_dir):
if "合并.xls" not in file : #因为合并后的文件和原始数据文件在同一路径下,这里判断下
print(file)
hebing_excels(file, 0)
elif "合并.xls" in os.listdir(file_dir) and file != "合并.xls" :
print(file)
workbook_hebing = xlrd.open_workbook("合并.xls")
table_hebing = workbook_hebing.sheet_by_index(0)
hebing_excels(file, table_hebing.nrows)
else:
pass
# break
workbook_write.save('合并.xls')
你覆盖写入了