Column problems in Python XLRD

Asked

Viewed 547 times

2

I am a beginner in Python and am trying to make a script to sum all the values of an excel column and write the sum value in the spreadsheet. I’m using the Python xlrd and xlwt packages. The code works well for the first column, but from the second no longer works, it always reports value 0. I hope someone more experienced can help me.

Thank you!

import xlwt
import xlrd

workbook_page = xlrd.open_workbook('page_level.xlsx')
worksheet_page = workbook_page.sheet_by_name('Daily External Referrers')
num_rows = worksheet_page.nrows - 1
curr_row = 0
num_cols = worksheet_page.ncols - 1
curr_col = 1
soma = 0

while curr_col < num_cols:
    curr_col = curr_col + 1
    while curr_row < num_rows:
        curr_row = curr_row + 1
        row = (worksheet_page.cell_value(curr_row, curr_col))
        if isinstance (row, float):
            soma = soma + row
        else:
            pass
    worksheet_page.write(num_rows+1, curr_col, soma)
worksheet_page.save('page_level.xlsx')

2 answers

0


Your problem seems to be in the form of progression of the loops:

while curr_col < num_cols:
    curr_col = curr_col + 1
    while curr_row < num_rows:
        curr_row = curr_row + 1

In the first iteration of the external loop, curr_col becomes real 1, and then curr_row goes from 0 to num_row through the internal loop. In the second iteration, curr_row already is num_rows, so that he doesn’t even enter the internal loop!

To solve you need to reset curr_row for 0 before starting the internal loop:

while curr_col < num_cols:
    curr_col = curr_col + 1
    curr_row = 0
    while curr_row < num_rows:
        curr_row = curr_row + 1

P.S. Are you sure what you want is to increase the value of the variable first and use it later? Note that the cell_value is based on zero, not one... so I think the right thing would be:

while curr_col < num_cols:
    curr_row = 0
    while curr_row < num_rows:
        # Seu código...
        curr_row = curr_row + 1 # No __final__ do loop
    # Mais código...
    curr_col = curr_col + 1 # No __final__ do loop

Or, more "pitonic":

for curr_col in range(num_cols):
    for curr_row in range(num_rows):
        ...

0

Thank you mgibsonbr!

I solved it this way:

while curr_col < num_cols:
    soma = 0
    curr_col = curr_col +1
    curr_row = 0
    while curr_row < num_rows:
        curr_row = curr_row + 1
        row = (worksheet_page.cell_value(curr_row, curr_col))
        if isinstance (row, float):
            soma = soma + row
            sheet.write(0, curr_col-2, worksheet_page.cell_value(0, curr_col))
            sheet.write(1, curr_col-2, soma)
            wb.save('kpis.xlsx')

        else:
            pass

Browser other questions tagged

You are not signed in. Login or sign up in order to post.