Setting values in openpyxl load_workbook, use_iter

2019-08-07 17:43发布

问题:

I want to read a xlsx file, change all the values less than say 0.0001 to 0.01. I can read the values and print them, but I can't change them ?

import pylab

from openpyxl import load_workbook
wb = load_workbook(filename = 'TF-Automation.xlsx', use_iterators=True)
ws = wb.get_sheet_by_name(name = 'Huvudmatris')

for row in ws.iter_rows():
    for cell in row:
        if cell.internal_value < 0.00001:
              cell.set_value = 0.000001      
        print cell.internal_value

回答1:

from the documentation : http://pythonhosted.org/openpyxl/api.html

 openpyxl.reader.excel.load_workbook(filename,use_iterators=False)[source] :
Open the given filename and return the workbook
Parameters:   

    filename (string) – the path to open
    use_iterators (bool) – use lazy load for cells

Return type:  
    openpyxl.workbook.Workbook

When using lazy load, all worksheets will be openpyxl.reader.iter_worksheet.IterableWorksheet and the returned workbook will be read-only.

don't use use_iterators=True . Also, if you need to call .save(filename) if you want to update the xlsx with your new values.