如何使用openpyxl设置上标 [英] How to set superscript using openpyxl

查看:101
本文介绍了如何使用openpyxl设置上标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用openpyxl 2.5.12和python 2.7.我使用的是Excel模板,需要保留标题的格式.有些上标值(例如Summary ^ 2)最终会变成Summary2.我知道样式是在openpyxl中的单元格级别设置的.还有其他解决方法吗?我真的需要这个,因为有很多标头和脚注作为上标

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

推荐答案

此代码将文本的对齐方式分配给上标,这基本上意味着使此单元格上标"为openpyxl

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')

可以在 xlsxwriter 中完成.因此,您想要做的是:

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()

这篇关于如何使用openpyxl设置上标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆