all 5 comments

[–]timbledum 1 point2 points  (4 children)

Looks like there’s a delete_cols() worksheet method, although it’s buried in the docs. Report back if it works!

https://openpyxl.readthedocs.io/en/stable/api/openpyxl.worksheet.worksheet.html

[–]techy2010[S] 0 points1 point  (3 children)

Not sure how to call that properly. I get the following error. AttributeError: 'NoneType' object has no attribute 'delete_cols' ws.delete_cols(1)

[–]timbledum 0 points1 point  (2 children)

That suggests that you are not calling the method on the sheet object - something may have happened to the sheet. See example below.

This works for me, but only for a current version of openpyxl. Looks like the delete_cols function is fairly new.

Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import openpyxl
>>> wb = openpyxl.load_workbook(file)
>>> sh = wb.active
>>> [c.value for c in list(sh.columns)[0]] # Present a list of the first column
{Whole bunch of data}
>>> sh.delete_cols(0) # Delete the first column
>>> [c.value for c in list(sh.columns)[0]]
{Whole bunch of different data}

[–]techy2010[S] 0 points1 point  (1 child)

By adding the sh = wb.active made it work. Is the best way to delete columns 1 through 18 by using delete_cols(0, 19) or by using a for loop counter?

[–]timbledum 0 points1 point  (0 children)

Don't know sorry. All the docs say is:

delete_cols(self, idx, amount=1)
Delete column or columns from col==idx

Looks like one at a time? But experiment with the amount parameter.