Python Forum
Error "list indices must be integers or slices, not str" - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Error "list indices must be integers or slices, not str" (/thread-39081.html)



Error "list indices must be integers or slices, not str" - dee - Dec-29-2022

I want to format Excel column to percent. The following code gave me "list indices must be integers or slices, not str" error. The __class__ of Column D is 'str'. Is it because the header is string?

Please advise how to format the columns with %. Thank you.

    wb = xl.load_workbook(fullpath)
    wsData = wb.worksheets["Data"]    
    wsData.Range("D2:O2").Style = "Percent"
or
    wsData.Range("D2:O2").NumberFormat = "0.00%"
See attachment for data.
[attachment=2169]


RE: Error "list indices must be integers or slices, not str" - deanhystad - Dec-29-2022

I'm assuming you are using openpyxl. I may be wrong since only 1 line in your post is valid based on "xl" being openpyxl.

The error is here:
wsData = wb.worksheets["Data"]
Worksheets is not a dictionary. It cannot be indexed by name. You can do this.
wsData = wb["Data"]
After you change that you'll soon learn that worksheets don't have a method "Range()". This is how you can set the number format for a range of cells.
import openpyxl as xl

wb = xl.load_workbook("test.xlsx")
sheet = wb["Sheet1"]
for cell in sheet["D2:O2"][0]:
    cell.number_format = "0.00%"
Have you looked through any of the openpyxl documentation?

https://openpyxl.readthedocs.io/en/stable/tutorial.html


RE: Error "list indices must be integers or slices, not str" - dee - Dec-30-2022

Thank you deanhystad. It works.