Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

Appending a excel spreadsheet as a new sheet to multiple spreadsheets using python

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...