0

I am writing a python code to read all the data in the xls file, iterate through all the elements in the excel file and randomize the C3 value for all the c3 elements within C1 and C2 value range. I have an issue with my current python code as only the last element in the column c3 is randomized. I am able to iterate through all the elements but have trouble randomizing the values for all the elements in column3.

import xlrd
from xlutils.copy import copy
import random

book = xlrd.open_workbook('temp.xlsx')
sheet = book.sheet_by_index(0)
nbook = copy(book)
nsheet = nbook.get_sheet(0)

for i in range(0, sheet.nrows):
    for j in range(0,sheet.ncols):
        min = sheet.cell_value(j,1)
        max = sheet.cell_value(j,2)

random = random.randint(min,max)
nsheet.write(i, 3, random)
nbook.save('new_temp.xlsx')
pigeonhands
  • 3,066
  • 15
  • 26
  • looks like an indentation issue to me – ScottC Feb 02 '23 at 23:54
  • If you are using Python 2.7 you should note **Being the last of the 2.x series, 2.7 received bugfix support until 2020. Support officially stopped January 1 2020, and 2.7.18 code freeze occurred on January 1 2020, but the final release occurred after that date.** Consider updating to Python 3 for better support. – moken Feb 02 '23 at 23:55
  • You have xlsx file in your code, my understanding was that xlrd had removed that support and only worked with xls files now. See https://xlrd.readthedocs.io/en/latest/ – moken Feb 03 '23 at 00:04
  • I get the following error with my new code "TypeError: coercing to Unicode: need string or buffer, int found" Is there a way to resolve this ? 'nsheet = nbook.get_sheet(0) for i in range(0, sheet.nrows): min = sheet.cell_value(j,1) max = sheet.cell_value(j,2) random = random.randint(min,max) nsheet.write(i, 3, random) nbook.save('new_temp.xlsx')' –  Feb 14 '23 at 21:00

0 Answers0