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

Discussão em 'Python' iniciado por Stack, Junho 21, 2025.

  1. Stack

    Stack Membro Participativo

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

    Continue reading...

Compartilhe esta Página