实现代码如下:
import xlrd import xlsxwriter import os # 打开一个Excel文件,创建一个工作簿对象 def open_xlsx(file): fh=xlrd.open_workbook(file) return fh # 获取sheet表的个数 def get_sheet_num(fh): x = len(fh.sheets()) return x # 读取文件内容并返回行内容 def get_file_content(file,shnum): fh=open_xlsx(file) table=fh.sheets()[shnum] num=table.nrows for row in range(num): rdata=table.row_values(row) datavalue.append(rdata) return datavalue def get_allxls(pwd): allxls = [] for path,dirs,files in os.walk(pwd): for file in files: allxls.append(os.path.join(path,file)) return allxls # 存储所有读取的结果 datavalue = [] pwd = "G:\\d" for fl in get_allxls(pwd): fh = open_xlsx(fl) x = get_sheet_num(fh) for shnum in range(x): print("正在读取文件:"+str(fl)+"的第"+str(shnum)+"个sheet表的内容...") rvalue = get_file_content(fl,shnum) # 定义最终合并后生成的新文件 endfile = "G:\\d\\concat.xlsx" wb1=xlsxwriter.Workbook(endfile) # 创建一个sheet工作对象 ws=wb1.add_worksheet() for a in range(len(rvalue)): for b in range(len(rvalue[a])): c=rvalue[a][b] ws.write(a,b,c) wb1.close() print("文件合并完成")
效果如下:
3. 将一个Excel表中的多个sheet表合并,并保存到同一个excel
实现代码如下:
import xlrd import pandas as pd from pandas import DataFrame from openpyxl import load_workbook excel_name = r"D:\pp.xlsx" wb = xlrd.open_workbook(excel_name) sheets = wb.sheet_names() alldata = DataFrame() for i in range(len(sheets)): df = pd.read_excel(excel_name, sheet_name=i, index=False, encoding='utf8') alldata = alldata.append(df) writer = pd.ExcelWriter(r"C:\Users\Administrator\Desktop\score.xlsx",engine='openpyxl') book = load_workbook(writer.path) writer.book = book # 必须要有上面这两行,假如没有这两行,则会删去其余的sheet表,只保留最终合并的sheet表 alldata.to_excel(excel_writer=writer,sheet_name="ALLDATA") writer.save() writer.close()
效果如下:
4. 将一个Excel表,按某一列拆分成多张表
实现代码如下:
import pandas as pd import xlsxwriter data=pd.read_excel(r"C:\Users\Administrator\Desktop\chaifen.xlsx",encoding='gbk') area_list=list(set(data['店铺'])) writer=pd.ExcelWriter(r"C:\Users\Administrator\Desktop\拆好的表1.xlsx",engine='xlsxwriter') data.to_excel(writer,sheet_name="总表",index=False) for j in area_list: df=data[data['店铺']==j] df.to_excel(writer,sheet_name=j,index=False) writer.save() #一定要加上这句代码,“拆好的表”才会显示出来
效果如下: