简体   繁体   English

在 Python 中使用 xlrd 和 xlwt 编写/创建工作表

[英]Writing/Creating a worksheet using xlrd and xlwt in Python

I'm trying to read multiple excel files with multiple sheets (sheet names are the same in all the excel files) and perform some calculations in each of the worksheet and save the calculation data from all the excel files corresponding to a worksheet into a new workbook.我正在尝试读取具有多个工作表的多个 excel 文件(所有 excel 文件中的工作表名称都相同)并在每个工作表中执行一些计算并将与工作表对应的所有 excel 文件中的计算数据保存到一个新的工作簿。 My little snippet to perform this is as follows:我执行此操作的小片段如下:

import xlrd
import xlwt
import os

wb2 = xlwt.Workbook()
wb2_name = 'AllSummary.xls'
pwd = os.getcwd()

for i in xrange(len(ListofExcelFiles)):
    fname = pwd + os.sep + ListofExcelFiles[i]
    wb1 = xlrd.open_workbook(fname)
    sheetNames = wb1.sheet_names()

    for j in xrange(len(sheetNames)):

        sheet = wb1.sheet_by_name(sheetNames[j])

        #<Read the Excel Data from Worksheet>
        #<Perform Calculation on Data Here>

        #<Create a new worksheet in wb2>
        sheet_all = wb2.add_sheet(sheetNames[j])

        #<Write the data to the worksheet>

wb2.save(wb2_name)
print "Output Excel File Saved!"

I understand that the first iteration on i , creates a new worksheet;我知道i的第一次迭代会创建一个新的工作表; which is being duplicated in the next iterations.在下一次迭代中被复制。 Can someone shed some light on how to overcome this duplication error?有人可以阐明如何克服这种重复错误吗? Any help will be much appreciated.任何帮助都感激不尽。

Thanks!谢谢!

You can simply add an if statement as below:您可以简单地添加一个if语句,如下所示:

if sheetNames[j] in wb2.sheet_names():
    sheet_all = wb2.sheet_by_name(sheetNames[j])

else
    sheet_all = wb2.add_sheet(sheetNames[j])

# Save your calculations' results in "sheet_all"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM