Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

python - Openpyxl setting number format

Could please someone show an example of applying the number format to the cell. For example, I need scientific format, form would be like '2.45E+05' but I couldn't figure a way how to do that in openpyxl.

I tried in several ways but they are all reporting errors when saving the workbook.

for example:

    import openpyxl as oxl

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

or this (here I'm trying to use some of the predefined number formats, I have also seen there is engineering format in builtins but don't know how to access it:

    nf = oxl.style.NumberFormat.FORMAT_NUMBER_00
    _cell.style.number_format = nf

In both cases I get the same error:

C:Python27openpyxlcell.pyc in is_date(self)
    408         """
    409         return (self.has_style
--> 410                 and self.style.number_format.is_date_format()
    411                 and isinstance(self._value, NUMERIC_TYPES))

AttributeError: 'str' object has no attribute 'is_date_format'

I have seen this question: Setting styles in Openpyxl but it doesn't help because I don't have to change any other formatting settings.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...