Excel操作
- 读取文件下所有文件 def readfile(self,path):
- 打开一个excel文件 def open_xls(self,file):
- 获取excel中所有sheet表 def getsheet(self,f):
- 获取sheet表的行数 def get_Allrows(self,f,sheet):
- 读取文件内容并返回行内容 def getFile(self,file,shnum):
- 获取sheet表的个数 def getshnum(self,f):
import os
import xlrd
import xlsxwriter
class excelutils:
def __init__(self):
super().__init__()
def readfile(self,path):
files=os.listdir(path)
list0=[]
list1=[]
for file in files:
if not os.path.isdir(file):
f=open(path+"/"+file)
print(f.name)
list1.append(f.name)
else:
path1=path+"/"+file
files1=os.listdir(path1)
for file1 in files1:
f=open(path1+"/"+file1)
s=[]
for i in f:
s.append(i)
list1.append(s)
return list1
def open_xls(self,file):
f=xlrd.open_workbook(file)
return f
def getsheet(self,f):
return f.sheets()
def get_Allrows(self,f,sheet):
table=f.sheets()[sheet]
return table.nrows
def getFile(self,file,shnum):
f=self.open_xls(file)
table=f.sheets()[shnum]
num=table.nrows
for row in range(num):
rdata=table.row_values(row)
datavalue.append(rdata)
return datavalue
def getFile(self,file,shnum,dv):
f=self.open_xls(file)
table=f.sheets()[shnum]
num=table.nrows
for row in range(num):
rdata=table.row_values(row)
dv.append(rdata)
return dv
def getshnum(self,f):
x=0
sh=self.getsheet(f)
for sheet in sh:
x+=1
return x
if __name__=='__main__':
e=excelutils()
allxls=e.readfile('C:/Users/xxx/xxxx/')
datavalue=['']
for fl in allxls:
f=e.open_xls(fl)
x=e.getshnum(f)
for shnum in range(x):
print("正在读取文件:"+str(fl)+"的第"+str(shnum)+"个sheet表的内容。。。。")
rvalue=e.getFile(fl,shnum)
endfile='C:/Users/xxx/xxxx/xxx/1.xlsx'
wb=xlsxwriter.Workbook(endfile)
ws=wb.add_worksheet()
for a in range(len(rvalue)):
for b in range(len(rvalue[a])):
c=rvalue[a][b]
ws.write(a,b,c)
wb.close()
print("文件合并完成")