How to clear a range of values in an Excel workbook using OpenPyXl

Andrew picture Andrew · Apr 12, 2016 · Viewed 25.3k times · Source

I have a workbook that I would like to clear a range of values with using OpenPyXI. So far I have the following:

# Import OpenPyXl module.
from openpyxl import load_workbook


# Load workbook.
wb = load_workbook(filename = 'testing.xlsx')

# Make a variable with a worksheet you want to view/modify.
sheet = wb['AR Cutoff']

# Change value of A3.
sheet['A3'] = 'Assigned value'

In short, I am trying to do in OpenPyXL the same thing the following VBA does:

Worksheets("Sheet1").Range("A1:G37").Clear

Thank you!

Answer

Florent B. picture Florent B. · Apr 12, 2016

It seems that the library doesn't have a method to clear or set a range directly. So your best chance is probably to clear the value for each cell:

for row in ws['A1:G37']:
  for cell in row:
    cell.value = None