Hi. I’m using xlwt package with Python to make an application that writes to excel files.
I have a function that returns the desired width of a cell so i can make the cell big enough to fit the text. However, my function breaks down when i’m writing text that’s in uppercase, as it then returns a width that is far smaller than the actual text.
I don’t know what’s the problem. Any advice would be much appreciated.
def getWidth(self, num_characters):
""" Returns the approximate width of a cell. """
return int((1+num_characters) * 256)
All you’re doing with the
getWidthfunction is guessing how much space you’re going to need. The reason you’re guessing is because each letter takes a different amount of space (“iiiii” takes up less room than “mmmmm”). Obviously, capital letters will take up more space.There are two simple (but not perfect) fixes to this problem:
The code for option 1 would be pretty similar to what you have already:
The code for option 2 would involve calling the
lowermethod on your string before inserting. It would look something like this: