简体   繁体   中英

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. 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; 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 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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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