[英]Appending a excel spreadsheet as a new sheet to multiple spreadsheets using python
I have over 300 unique ".xlsx" spreadsheets. 我有300多个独特的“ .xlsx”电子表格。 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.
我还有另一个电子表格(一个解释字段名称的数据字典),我想作为新的表格(标签)附加到300个唯一的电子表格中。
Is there a relatively simple way to do this task in python? 有没有一种相对简单的方法可以在python中执行此任务?
Here's how you could do it with Python-Excel 使用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.
然后,它复制“ ToBeAppended.xlsx”的第一张纸并收集其中的所有数据。 Then it gathers then name of files it needs to change (which for me was "1.xlsx" and so on).
然后,它收集然后需要更改的文件名(对我来说是“ 1.xlsx”,依此类推)。 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. 您会注意到它保存了一个“ .xls”文件。 This is a limitation of the package, and I don't know any way around it.
这是该程序包的限制,我对此一无所知。 Sorry
抱歉
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.