Openpyxl setting number format

假如想象 提交于 2019-11-30 08:04:41
qryckbosch

This answer works with openpyxl 2.0. (The previously accepted answer does not.)

The number_format can be changed directly.

The given example becomes:

from openpyxl import Workbook

wb = Workbook()
ws = wb.create_sheet(title='testSheet')
_cell = ws.cell('A1')
_cell.number_format = '0.00E+00'
Renesis

Note: this answer worked with earlier versions of openpyxl, but does not work with openpyxl 2.0

This is how to do it:

    _cell.style.number_format.format_code = '0.00E+00' 

For openpyxl version 2.6.2: note the float display depends on the magnitude when in a python shell, or idle, or ipython session,

>>> wb = load_workbook('tmp.xlsx')
>>> ws = wb[wb.sheetnames[0]]
>>> c21 = ws.cell(2,1)
>>> c21.value
'43546'
>>> c21.value = int(c21.value)
>>> c21.value
43546
>>> c21.value = 134352345235253235.235235
>>> c21.number_format = '0.000E+00'
>>> c21.value
1.3435234523525323e+17
>>> c21.value = 534164134.6643
>>> c21.value
534164134.6643
>>> wb.save('tmp_a.xlsx')
>>> wb.close()

But do not be dismayed, because the '0.000E+00' format will be displayed correctly when you re-open the spreadsheet with MS-Excel or LibreOffice-Calc or Gnumeric. Just remember to save the workbook.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!