Search code examples
pythonexcelxlrd

Problems whith columns in Python xlrd


I am a Python Beginner and I'm trying to make a script to sum all values in a column of a excel spereadsheet, and then write this value. I'm using xlrd and xlwt python packages. It works well for the first columm, but it doesn't works to the second untill the last column. Here is my code. Hope someone can help me.

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')

Solution

  • I don't think you can directly edit the excel workbook you're reading with xlrd, you have to copy it to new workbook and edit that.

    Just a prefence as well, but I would also use for loops rather than while loops just for ease.

    I can't test it at the moment, but maybe try something more like this?

    import xlwt, xlrd
    from xlutils.copy import copy
    
    read_workbook_page = xlrd.open_workbook('page_level.xlsx')
    
    workbook_page = copy(read_workbook_page)
    worksheet_page = workbook_page.sheet_by_name('Daily External Referrers')
    
    num_rows = worksheet_page.nrows - 1
    num_cols = worksheet_page.ncols - 1
    
    for row in range(num_rows):
         column_sum = 0
         for column in range(1, num_cols):
              column_sum += worksheet_page.cell_value( row, column )
         worksheet_page.write(row, num_cols, column_sum )
    
    worksheet_page.save('page_level.xlsx')