Home > Blockchain >  Replace special character "-" with 0 integer value
Replace special character "-" with 0 integer value

Time:01-20

I am traversing an excel sheet using openpyxl() and copying over the contents to another excel.

import openpyxl

NEW_EXCEL_FILE = openpyxl.load_workbook('workbook1.xlsx')
NEW_EXCEL_FILE_WS = NEW_EXCEL_FILE.active
SHEET = NEW_EXCEL_FILE.get_sheet_by_name(sheet_name)
for i,row in enumerate(SHEET.iter_rows()):
   for j,col in enumerate(row):
      col.value = col.value.replace("-", 0)
      NEW_FILE_SHEET.cell(row=i 1,column=j 1).value = col.value
      
NEW_EXCEL_FILE.save('workbook1.xlsx')

I need to replace the cell contents which has "-" to 0. when i tried using col.value.replace("-", 0), it is not accepting int value.

I am getting the below exception, TypeError: replace() argument 2 must be str, not int

please help.

Thanks,

CodePudding user response:

you can do it by using .cell(row=i, column=j).value and for loop. So you can try this:

import openpyxl

NEW_EXCEL_FILE = openpyxl.load_workbook(filename="workbook1.xlsx")
NEW_EXCEL_FILE_WS = NEW_EXCEL_FILE.active
num_columns = NEW_EXCEL_FILE_WS.max_column
num_row = NEW_EXCEL_FILE_WS.max_row
for i in range(1, num_row 1):
    for j in range(1, num_columns 1):
        if NEW_EXCEL_FILE_WS.cell(row=i, column=j).value == "-":
            NEW_EXCEL_FILE_WS.cell(row=i, column=j).value = 0

NEW_EXCEL_FILE.save(filename="workbook1.xlsx")
  • Related