Stefano Potter
Stefano Potter

Reputation: 3577

Replace specific values in openpyxl

I have a excel file that looks like this:

   1984    1      1
   1985    1      1

I want to change all of the values in column 2 to 0 but I am not sure how to loop through rows.

I have tried:

import openpyxl

wb=openpyxl.load_workbook(r'C:\file.xlsx')
ws=wb['Sheet1']
for row in ws:
     row = [x.replace('1', '0') for x in row]

but that must not be how you loop through rows.

my desired out put is:

1984 0 1
1985 0 1

Upvotes: 2

Views: 10503

Answers (1)

Augustine C
Augustine C

Reputation: 844

You can do something like this:

import openpyxl
excelFile = openpyxl.load_workbook('file.xlsx')
sheet1 = excelFile.get_sheet_by_name('Sheet1')
currentRow = 1
for eachRow in sheet1.iter_rows():
    sheet1.cell(row=currentRow, column=2).value = "0"
    currentRow += 1
excelFile.save('file.xlsx')

Updates 2nd column to all zeros.

Upvotes: 6

Related Questions