Search code examples
python-2.7xlrdxlw

Reading Multiple excel files in a directory and write a particular cell value to another excel sheet


I need to read a particular cell value from 100 excel workbooks present in a directory, and write that data to columns in a separate excel sheet. Here is what I did which produced errors:

#!/usr/bin/env python
import os
import xlwt
import xlrd

index=0
workbook = xlwt.Workbook()
Testsheet = workbook.add_sheet('test')
print "Enter the row you want"
row=input()
print "Enter the column you want"
col=input()

for file in os.listdir('.'):
    wb = xlrd.open_workbook(file)
    wb.sheet_names()
    sh = wb.sheet_by_name(u'Sheet1')
    data = sh.cell(row,col).value
    Testsheet.write(0, index, data)
    index=index+1

workbook.save('Test.xls')

Can anyone help to do this successfully?


Solution

  • This is working fine !!!

    #!/usr/bin/env python
    import os
    import xlwt
    import xlrd
    
    
    index=0
    
    workbook = xlwt.Workbook()
    Testsheet = workbook.add_sheet('test')
    print "Enter the row you want"
    row=input()
    print "Enter the column you want"
    col=input()
    path= 'E:/Test'
    for root,dirs,files in os.walk(path):
    xlsfiles=[ _ for _ in files if _.endswith('.xls') ]
    for xlsfile in xlsfiles:
        wb = xlrd.open_workbook(os.path.join(root,xlsfile))
        n = len(wb.sheets())
    for s in range(n) :
            sheet = wb.sheet_by_index(s)
            data=sheet.cell(row,col).value
            print data
            Testsheet.write(index, 0, data)
        index=index+1
    
    workbook.save('Test.xls')