How to clear data from Excel worksheets

Hi,
I am using a loop to clear contents of a worksheet. I am not sure if this is efficient way to do. Can any please guide me with more efficient way to do it.

import openpyxl
wbkName = r'\\AA\ AA \ AA \ AA \Python Chart Data.xlsx'# Please change path
wbk = openpyxl.load_workbook(wbkName)

#This loop is used to clear contents of worksheets, I am trying more efficient way for this.
for wks in wbk.worksheets:
    for row in wks['A1:J10']:
      for cell in row:
        cell.value = None #

for wks in wbk.worksheets:# This will write for all the worksheets in workbook
	for myRow in range(1, 6):# 6 will give results till row 5 not 6
		for myCol in range(1,11):# 11 will give data till column 10
			wks.cell(row=myRow, column=myCol).value = myRow 
            
wbk.save(wbkName)
wbk.close ()

Please try this code with your variables and let me know if it is resolved:

#This code will clear 6 columns and 100 rows so that when we enter new data or list in excel it starts from the beginning.

import openpyxl
wb=openpyxl.load_workbook('openpyxl.xlsx')
ws=wb.get_sheet_by_name('Raw Data')

ws.delete_cols(1, 6)
ws.delete_rows(1, 100)
1 Like

Hi Rupesh,

Thanks for the help. Sorry for late reply. Have a nice day ahead. :slight_smile:

Hi Rupesh,
I have been trying this on an .xlsm file, nothing happens, and no error message.
you have any idea why nothing happens?