python将excel每行形成新表格_使用python将excel电子表格作为新工作表添加到多个电子表格...

I have over 300 unique ".xlsx" spreadsheets. I have another spreadsheet (a data dictionary explaining field names) that I would like to append as a new sheet (tab) to each of the 300 unique spreadsheets.

Is there a relatively simple way to do this task in python?

解决方案

Here's how you could do it with Python-Excel

import xlrd

import xlwt

from xlutils.copy import copy

import os

if not os.path.exists("/new"): os.makedirs("new")

toBeAppended = xlrd.open_workbook("ToBeAppended.xlsx")

sheetToAppend = toBeAppended.sheets()[0] #If you don't want it to open the first sheet, change the 0 accordingly

dataTuples = []

for row in range(sheetToAppend.nrows):

for col in range(sheetToAppend.ncols):

dataTuples.append((row, col, sheetToAppend.cell(row,col).value))

#You need to change this line!

wbNames = ["{}.xlsx".format(num) for num in range(1,7)]

for name in wbNames:

wb = copy(xlrd.open_workbook(name))

newSheet = wb.add_sheet("Appended Sheet")

for row, col, data in dataTuples:

newSheet.write(row, col, data)

wb.save("new/"+name.split('.')[0]+".xls")

So this creates a new folder for your new sheets (just in case it doesn't work). Then it copies the the first sheet of "ToBeAppended.xlsx" and gathers all the data in it. Then it gathers then name of files it needs to change (which for me was "1.xlsx" and so on). Then it creates a copy of each workbook it needs to edit, adds the sheet, and writes all the data too it. Finally, it saves the file.

You'll note that it saves a ".xls" file. This is a limitation of the package, and I don't know any way around it. Sorry

Hope this helps.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值