Python Forum

Full Version: Error "list indices must be integers or slices, not str"
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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]
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
Thank you deanhystad. It works.