Python-2016-10-23-作业

浏览: 902

Excel表格的合并:

要点:

    1. 多个Excel文件

    2. 每个Excel表格多个Sheet

    3. 合并写入一个Excel文件中

import xlrd,xlwt

inputfiles = ['first.xlsx','second.xlsx','third.xlsx']
outputfile = 'result.xls'
wb = xlwt.Workbook()
outputList = []


def open_excel(file):
resultRowIndex = 0;
workbook = xlrd.open_workbook(filename=file)
for sheetname in workbook.sheet_names():
worktable = workbook.sheet_by_name(sheetname)
for rownum in range(worktable.nrows):
outputList.append(worktable.row_values(rownum))

def open_inputs(inputfiles):
for index in range(len(inputfiles)):
try:
print('尝试打开文件'+inputfiles[index]+"读取!")
open_excel(inputfiles[index])
print('读取文件'+inputfiles[index]+"成功!")
except Exception as err:
print('读取文件'+inputfiles[index]+"失败!")

def writeFile(outputList):
ws = wb.add_sheet("result")
for rowIndex in range(len(outputList)):
for colIndex in range(len(outputList[rowIndex])):
ws.write(rowIndex, colIndex, outputList[rowIndex][colIndex])
try:
wb.save(outputfile)
print('文件写入成功')
except:
print('文件写入失败!')

open_inputs(inputfiles)
writeFile(outputList)
推荐 0
本文由 ☆→宝山←☆ 创作,采用 知识共享署名-相同方式共享 3.0 中国大陆许可协议 进行许可。
转载、引用前需联系作者,并署名作者且注明文章出处。
本站文章版权归原作者及原出处所有 。内容为作者个人观点, 并不代表本站赞同其观点和对其真实性负责。本站是一个个人学习交流的平台,并不用于任何商业目的,如果有任何问题,请及时联系我们,我们将根据著作权人的要求,立即更正或者删除有关内容。本站拥有对此声明的最终解释权。

0 个评论

要回复文章请先登录注册