상세 컨텐츠

본문 제목

Openpyxl 설정 숫자 형식

openpyxl

by 한판님 2021. 10. 15. 15:50

본문

셀에 숫자 형식을 적용하는 방법을 알고 싶습니다!

 

예를 들어, 과학 형식이 필요합니다.

형식은 '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'

 

이 질문을 보았습니다. Openpyxl에서 스타일을 설정 하지만 다른 서식 설정을 변경할 필요가 없기 때문에 도움이 되지 않습니다.

 

 

 

(답변)

이 답변은 openpyxl 2.0에서 작동합니다.

number_format직접 변경할 수 있습니다. 주어진 예는 다음과 같습니다.

from openpyxl import Workbook

wb = Workbook()

ws = wb.create_sheet(title='testSheet')

_cell = ws.cell('A1')

_cell.number_format = '0.00E+00'

 

참고: 이 답변은 이전 버전의 openpyxl에서 작동 했지만 openpyxl 2.0에서는 작동하지 않습니다.

방법은 다음과 같습니다.

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

 

 

openpyxl 버전 2.6.2의 경우: float 표시는 파이썬 셸, 유휴 또는 ipython 세션에 있을 때 크기에 따라 달라집니다.

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

 

그러나 MS-Excel, LibreOffice-Calc 또는 Gnumeric으로 스프레드시트를 다시 열면 '0.000E+00' 형식이 올바르게 표시되므로 놀라지 마십시오. 통합 문서를 저장하는 것을 잊지 마십시오.

 

penpyxl 버전 3(v3.0.9)을 사용하여 셀의 서식을 직접 지정하려면 다음 코드가 필요했습니다.

from openpyxl import Workbook

wb = Workbook()

ws = wb.create_sheet(title='testSheet')

_cell = ws['A1']

_cell.number_format = '0.00E+00'

 

셀은 다음과 같이 직접 서식을 지정할 수 있습니다.

ws['A1'].number_format = '0.00E+00'

문서에는 사용 가능한 다양한 숫자 형식이 표시되어 있으며 몇 가지가 있습니다. https://openpyxl.readthedocs.io/en/stable/_modules/openpyxl/styles/numbers.html

 

 

 

참조 :https://stackoverflow.com/questions/12387212/openpyxl-setting-number-format

관련글 더보기