今天就跟大家聊聊有关怎么在Python中横向合并excel文件,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
数据示意:
具有多个
代码:
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 12 11:19:03 2017
@author: Li Ying
"""
#读取第一列作为合并后表格的第一列
from pandas import read_csv
df = read_csv(r'E:\excel\vb\excel1.csv',header=None)
sample_name = df[0]
file="combine"
filedestination = "E://excel//"
import glob
#from numpy import *
filearray=[]
for filename in glob.glob(r'E:\excel\*.xlsx'):
filearray.append(filename)
#以上是从excel 文件夹下读取所有excel表格,并将所有的名字存储到列表filearray
print("在默认文件夹下有%d个文档哦"%len(filearray))
ge=len(filearray)
matrix = [None]*ge
#实现读写数据
#下面是将所有文件读数据到三维列表cell[][][]中(不包含表头)
import xlrd
for i in range(ge):
fname=filearray[i]
bk=xlrd.open_workbook(fname)
try:
sh=bk.sheet_by_name("Sheet1")
except:
print ("在文件%s中没有找到sheet1,读取文件数据失败,要不你换换表格的名字?" %fname)
ncols=sh.ncols
matrix[i] = [0]*(ncols-1)
nrows=sh.nrows
for m in range(ncols-1):
matrix[i][m] = ["0"]*nrows
for k in range(1,ncols):
for j in range(0,nrows):
matrix[i][k-1][j]=sh.cell(j,k).value
import xlwt
filename=xlwt.Workbook()
sheet=filename.add_sheet("hel")
#下面是把第一列写上
for i in range(0,len(sample_name)):
sheet.write(i,0,sample_name[i])
#求和前面的文件一共写了多少列
zh=1
for i in range(ge):
for j in range(len(matrix[i])):
for k in range(len(matrix[i][j])):
sheet.write(k,zh,matrix[i][j][k])
zh=zh+1
print("我已经将%d个文件合并成1个文件,并命名为%s.xlsx."%(ge,file))
filename.save(filedestination+file+".xls")
合并结果:
看完上述内容,你们对怎么在Python中横向合并excel文件有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。