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
Here is my code:
import openpyxl
from pptx import Presentation
from pptx.util import Inches , Pt
from pptx.dml.color import ColorFormat, RGBColor
from pptx.util import Cm
prs = Presentation()
presentation = Presentation()
prs.slide_width = Inches(12.992126)
prs.slide_height = Inches(7.5)
title_slide_layout = prs.slide_layouts[0]
slide = prs.slides.add_slide(title_slide_layout)
title = slide.shapes.title
subtitle = slide.placeholders[1]
title.left = Cm(7)
title.height = Cm(17)
title.width = Cm(20)
subtitle.top = Cm(12)
subtitle.left = Cm(7)
subtitle.height = Cm(5)
subtitle.width = Cm(20)
wb = openpyxl.load_workbook(r'C:\my files.xlsx')
active_sheet = wb['TCCONNAISSEURS']
# wb.active first sheet
sheet = wb.active
subtitle.text = active_sheet['C8'].value
It actually works perfectly with text but I can't have my '29%' on the presentation.
How should I re-write this part of the code so it works ? Please let me know if they have found similar problems or not. I appreciate your help.
CodePudding user response:
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.