Search code examples
pythonexcelpowerpointpython-pptx

Add percentage numbers from a cell in PPTX


I'm a novice in Python, and I'm struggling with pptx rn.

I have an xlsx file and I want to import a single percentage number from a cell in my presentation.

Here is the traceback:

line 40, in to_unicode
    raise TypeError("expected unicode string, got %s value %s" % (type(text), text))
TypeError: expected unicode string, got <class 'float'> value 0.29

Solution

  • Try:

    subtitle.text = str(active_sheet['C8'].value)
    

    as a start. This should avoid the exception, but might not give you the exact representation you want.

    I expect it will give you "0.29", but let's come back to that. The reason you are getting the exception is because you are assigning a numeric (float) value to a property that expects a str value. Converting it to string using the built-in str() function takes care of that.

    To get a percentage representation, try:

    subtitle.text = "{:.0%}".format(active_sheet['C8'].value)
    

    There are other ways of what is called interpolating strings from numbers in Python that you can find on search, but this is a good one in this case.