Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loop excel sheets and rows in Python

Tags:

python

excel

I have a simple code:

import xlrd  
book = xlrd.open_workbook('import.xls')  
for sheet in book.sheets():  
    for row in range(sheet.nrows):    
        print sheet.row(row)  

but it's printing:

sheet1: row1  
sheet1: row2  
sheet1: row3  

sheet2: row1  
sheet2: row2   
sheet2: row3  
and etc   

I need to change this code to print this:

sheet1: row1  
sheet2: row1  
sheet3: row1  

sheet1: row2  
sheet2: row2  
sheet3: row2  
and etc.  

Any help would be highly appreciated. Thanks

like image 535
user2745454 Avatar asked Mar 23 '23 13:03

user2745454


1 Answers

import xlrd
book = xlrd.open_workbook('import.xls')

max_nb_row = 0
for sheet in book.sheets():
  max_nb_row = max(max_nb_row, sheet.nrows)

for row in range(max_nb_row) :
  for sheet in book.sheets() :
    if row < sheet.nrows :
      print sheet.row(row)
like image 136
Jyhess Avatar answered Apr 05 '23 23:04

Jyhess