0

I am using openpyxl 2.5.12 and python 2.7. I am using a excel template and need to retain the format of headers. There are some superscript values like Summary^2 that just end up as Summary2. I understand that styles are set at a cell level in openpyxl. Is there any other workaround for this? i really need this since there are many headers and footnotes as superscripts

tried setting different styles, but it either makes the whole cell value as superscript or none. Not just the last value as needed

D3110
  • 15
  • 3
  • Possible duplicate of [Editing workbooks with rich text in openpyxl](https://stackoverflow.com/questions/28774757/editing-workbooks-with-rich-text-in-openpyxl) – Charlie Clark May 17 '19 at 08:48

1 Answers1

0

This code assigns the alignment of your text to superscript which basiclly means "make this cell superscript" to openpyxl

#Import openpyxl
from openpyxl import *

#Get the workbook and set the work sheet
workbook = Workbook()
ws = wb.active

#Add some data
ws.append(['Hello', 'World'])

#Change vertAlign so that the text is superscript
ws['A1'].vertAlign = "superscript"

#Save the workbook
workbook.save('file_name.xlsx')

EDIT: This can be done in xlsxwriter. So what you're looking to do is:

import xlsxwriter

workbook = xlsxwriter.Workbook('rich_strings.xlsx')
worksheet = workbook.add_worksheet()

worksheet.set_column('A:A', 30)
superscript = workbook.add_format({'font_script': 1})
worksheet.write_rich_string('cell',
                            'hello',
                            superscript, 'world'
)
workbook.close()
zurgeg
  • 510
  • 6
  • 18
  • Thanks Jon, but this is something i know and i mentioned in my question. my question was more how to keep 'hello' as normal and 'world' as superscript when they are both in the same cell – D3110 May 17 '19 at 14:40
  • It seems that rich text formatting (basically what you're trying to do) has not been added in openpyxl. You should open an issue on GitHub [here](https://github.com/chronossc/openpyxl/issues) – zurgeg Jun 12 '19 at 19:38
  • Found an issue on GitHub [here](https://github.com/chronossc/openpyxl/issues/46) – zurgeg Apr 12 '20 at 16:10
  • @D3110 edited my answer and now it has a fix, might not work with Python 2, it's reached it's end of life though so you should upgrade. – zurgeg Apr 20 '20 at 01:06