python实现表格合并

应用场景:有一个文件夹存放着表结构相同的大量表格,现将所有表格合并,表头保留

代码实现:

import os
import os.path
import xdrlib ,sys
import xlrd
import csv

rootdir="e:\min5\sh"
csvfile=file('bigdata.csv','ab+')

实现excel转换成csv,并且进行合并  
>> def writeSingleData2Csv(file,colnameindex=0):
csvFile = 'bigdata.csv'
fileStream = open(csvFile,'ab+')
print csvFile
write = csv.writer(fileStream)
data=loadSingleExcel(file)
header = readHeader(data)
writeHead2csv(header,write)
nrows = data.nrows
for rownum in range(1,nrows):
rowdata = data.row_values(rownum)
writeData2csv(rowdata,write)
fileStream.close()

>>> def writeAllData2Csv(path='e:\min5\sh'):
for parent,dirnames,filenames in os.walk(path):
for filename in filenames:
writeSingleData2Csv(path+'\\'+filename,colnameindex=0)

def loadSingleExcel(file=“”):
try:
data=xlrd.open_workbook(file).sheets()[0]
return data
except Exception,e:
print str(e)

def readHeader(data,colnameindex=0):
head=[]
head=data.row_values(0)
return head

def writeHead2csv(data,write):
write.writerow(data)

def writeData2csv(data,write):
write.writerow(data)


执行:writeAllData2Csv()

注:python的缩进代表着特别含义

你可能感兴趣的:(python实现表格合并)