gpt4 book ai didi

python - openpyxl设置数字格式

转载 作者:IT老高 更新时间:2023-10-28 20:31:07 27 4
gpt4 key购买 nike

请有人展示一个将数字格式应用于单元格的示例。例如,我需要科学格式,格式类似于 '2.45E+05' 但我想不出如何在 openpyxl 中做到这一点。

我尝试了几种方法,但保存工作簿时都报错。

例如:

    import openpyxl as oxl

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

或者这个(这里我尝试使用一些预定义的数字格式,我也看到内置有工程格式但不知道如何访问它:

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

在这两种情况下,我都会遇到相同的错误:

C:\Python27\openpyxl\cell.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'

我看过这个问题:Setting styles in Openpyxl但这无济于事,因为我不必更改任何其他格式设置。

最佳答案

此答案适用于 openpyxl 2.0。 (previously accepted answer 没有。)

number_format可以直接更改。

给定的例子变成:

from openpyxl import Workbook

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

关于python - openpyxl设置数字格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12387212/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com