old-willow
old-willow

Reputation: 111

Python, openpyxl: how to preserve formating in the cell?

I am importing some data from xslx file to Django model.

Everything works perfectly except that if cell have some formatting of "superscript" or "subscript" it loses that formatting.

Is there a way to preserve the style formatting of the value in the cell?

m2 becomes simply m2

Upvotes: 1

Views: 625

Answers (1)

stovfl
stovfl

Reputation: 15513

If I open the xml in xlsx file I see the tag vertAlign val="superscript"

Comments: I have to use Python 2 and openpyxl 2.2. And the cell value is not just '2' or '3' it is 'm^2' or 'm^3' or what ever,

This is Character Format, you can't pass Character Format to Django. Only the value which ist ^2 or ^3.

For instance this would help:

import re
if vertAlign == superscript:
    value = re.sub('\^2', '²', cell.value)
    value = re.sub('\^3', '³', value)

This changes all simulated superscipt(2|3), to unicode(²|³).

Tested with Python:3.4.2 - openpyxl:2.4.1 - LibreOffice: 4.3.3.2
Should also work with your Python 2 and openpyxl 2.2.

Upvotes: 2

Related Questions