Openpyxl에서 스타일 설정
Openpyxl 스타일 설정에 대한 조언이 필요합니다.
그 번호가셀 형식을 설정할 수 있지만 글꼴 색상 및 속성(굵은 글씨 등) 설정도 필요합니다.style.py 클래스가 있습니다만, 셀의 스타일 속성을 설정할 수 없는 것 같고, openpyxl 소스 코드를 만지작거리고 싶지 않습니다.
이 문제에 대한 해결책을 찾은 사람이 있나요?
openpyxl 버전 1.5.7에서 다음 워크시트 스타일 옵션을 적용했습니다.
from openpyxl.reader.excel import load_workbook
from openpyxl.workbook import Workbook
from openpyxl.styles import Color, Fill
from openpyxl.cell import Cell
# Load the workbook...
book = load_workbook('foo.xlsx')
# define ws here, in this case I pick the first worksheet in the workbook...
# NOTE: openpyxl has other ways to select a specific worksheet (i.e. by name
# via book.get_sheet_by_name('someWorksheetName'))
ws = book.worksheets[0]
## ws is a openpypxl worksheet object
_cell = ws.cell('C1')
# Font properties
_cell.style.font.color.index = Color.GREEN
_cell.style.font.name = 'Arial'
_cell.style.font.size = 8
_cell.style.font.bold = True
_cell.style.alignment.wrap_text = True
# Cell background color
_cell.style.fill.fill_type = Fill.FILL_SOLID
_cell.style.fill.start_color.index = Color.DARKRED
# You should only modify column dimensions after you have written a cell in
# the column. Perfect world: write column dimensions once per column
#
ws.column_dimensions["C"].width = 60.0
참고로 색깔의 이름은openpyxl/style.py...X11 색명의 추가 색상으로 패치 할 때도 있습니다.
class Color(HashableObject):
"""Named colors for use in styles."""
BLACK = 'FF000000'
WHITE = 'FFFFFFFF'
RED = 'FFFF0000'
DARKRED = 'FF800000'
BLUE = 'FF0000FF'
DARKBLUE = 'FF000080'
GREEN = 'FF00FF00'
DARKGREEN = 'FF008000'
YELLOW = 'FFFFFF00'
DARKYELLOW = 'FF808000'
openpyxl 버전 2.4.1 이상의 경우 아래 코드를 사용하여 글꼴 색상을 설정합니다.
from openpyxl.styles import Font
from openpyxl.styles.colors import Color
ws1['A1'].font = Font(color = "FF0000")
다양한 색상의 16진수 코드는http://http://dmcritchie.mvps.org/excel/colors.htm 에서 확인할 수 있습니다.
openpyxl 2.0에서는 스타일은 변하지 않습니다.
를 가지고 있는 경우cell굵은 글씨 텍스트는 다음과 같이 설정할 수 있습니다.
cell.style = cell.style.copy(font=cell.style.font.copy(bold=True))
네, 짜증나요.
openpyxl 2.0에서는 새로운 스타일 객체를 만들고 셀의 속성에 할당함으로써 셀 스타일을 설정할 수 있습니다.
몇 가지 스타일 객체가 있습니다.Font,PatternFill,Border,그리고.Alignment.의사를 참조해 주세요.
셀의 스타일 특성을 변경하려면 먼저 셀에서 기존 스타일 객체를 복사하고 특성 값을 변경하거나 원하는 설정으로 새 스타일 객체를 작성해야 합니다.그런 다음 셀에 새 스타일 객체를 지정합니다.
글꼴을 셀 A1의 굵은 글씨 및 기울임꼴로 설정하는 예:
from openpyxl import Workbook
from openpyxl.styles import Font
# Create workbook
wb = Workbook()
# Select active sheet
ws = wb.active()
# Select cell A1
cell = ws['A1']
# Make the text of the cell bold and italic
cell.font = cell.font.copy(bold=True, italic=True)
이 기능은 몇 번 변경된 것 같습니다.openpyxl 2.5.0을 사용하고 있는데, 다음과 같이 스트라이크 스루 옵션을 설정할 수 있었습니다.
new_font = copy(cell.font)
new_font.strike = True
cell.font = new_font
이전 버전(1.9~2.4?)에는,copymethod는 현재 사용되지 않으며 경고를 발생시킵니다.
cell.font = cell.font.copy(strike=True)
1.8 이전 버전에서는 글꼴이 변경 가능하기 때문에 다음과 같이 할 수 있습니다.
cell.font.strike=True
이것으로 에러가 발생합니다.
새로운 2021 OpenPyXl 글꼴 변경 방법 업데이트:
sheet.cell.font = Font(size=23, underline='single', color='FFBB00', bold=True, italic=True)
풀코드:
import openpyxl # Connect the library
from openpyxl import Workbook
from openpyxl.styles import PatternFill # Connect cell styles
from openpyxl.workbook import Workbook
from openpyxl.styles import Font, Fill # Connect styles for text
from openpyxl.styles import colors # Connect colors for text and cells
wb = openpyxl.Workbook() # Create book
work_sheet = wb.create_sheet(title='Testsheet') # Created a sheet with a name and made it active
work_sheet['A1'] = 'Test text'
work_sheet_a1 = work_sheet['A5'] # Created a variable that contains cell A1 with the existing text
work_sheet_a1.font = Font(size=23, underline='single', color='FFBB00', bold=True,
italic=True) # We apply the following parameters to the text: size - 23, underline, color = FFBB00 (text color is specified in RGB), bold, oblique. If we do not need a bold font, we use the construction: bold = False. We act similarly if we do not need an oblique font: italic = False.
# Important:
# if necessary, the possibility of using standard colors is included in the styles, but the code in this case will look different:
work_sheet_a1.font = Font(size=23, underline='single', color=colors.RED, bold=True,
italic=True) # what color = colors.RED — color prescribed in styles
work_sheet_a1.fill = PatternFill(fill_type='solid', start_color='ff8327',
end_color='ff8327') # This code allows you to do design color cells
openpyxl 의사가 말한 것처럼:
이것은 오픈 소스 프로젝트이며, 여가 시간에 자원 봉사자들이 관리합니다.이는 원하는 특정 기능 또는 기능이 누락되었음을 의미할 수 있습니다.
openpyxl 소스코드를 확인했더니 다음과 같습니다.
openpyxl 1.8.x까지 스타일은 변동 가능합니다.이러한 속성은 다음과 같이 직접 할당할 수 있습니다.
from openpyxl.workbook import Workbook
from openpyxl.style import Color
wb = Workbook()
ws = wb.active
ws['A1'].style.font.color.index = Color.RED
하지만 openpyxl 1.9부터 스타일은 변하지 않습니다.
스타일은 객체 간에 공유되며 한 번 할당된 스타일은 변경할 수 없습니다.이렇게 하면 셀을 하나만 사용하는 것이 아니라 여러 셀의 스타일을 변경하는 등의 원치 않는 부작용을 방지할 수 있습니다.
새 스타일 오브젝트를 작성하려면 오브젝트를 직접 할당하거나 기존 셀의 스타일에서 새로운 속성으로 오브젝트를 복사하여 질문에 답할 수 있습니다(중국어 사용 금지).
from openpyxl.styles import colors
from openpyxl.styles import Font, Color
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
a1 = ws['A1']
d4 = ws['D4']
# create a new style with required attributes
ft_red = Font(color=colors.RED)
a1.font = ft_red
# you can also do it with function copy
ft_red_bold = ft_red.copy(bold=True)
# you can copy from a cell's style with required attributes
ft_red_sigle_underline = a1.font.copy(underline="single")
d4.font = ft_red_bold
# apply style to column E
col_e = ws.column_dimensions['E']
col_e.font = ft_red_sigle_underline
셀' 스타일에는 글꼴, 채우기, 테두리, 정렬, 보호 및 number_format 속성이 포함됩니다. 마크를 켜주세요.openpyxl.styles.
하고 둘 다. 단, number_format 은 number_format입니다. 을 사용하다stringdiscloss.discloss.
몇 가지 사전 정의된 숫자 형식을 사용할 수 있으며 숫자 형식을 문자열 유형으로 정의할 수도 있습니다. 마크를 켜주세요.openpyxl.styles.numbers.
from openpyxl.styles import numbers
# use pre-defined values
ws.cell['T49'].number_format = numbers.FORMAT_GENERAL
ws.cell(row=2, column=4).number_format = numbers.FORMAT_DATE_XLSX15
# use strings
ws.cell['T57'].number_format = 'General'
ws.cell(row=3, column=5).number_format = 'd-mmm-yy'
ws.cell['E5'].number_format = '0.00'
ws.cell['E50'].number_format = '0.00%'
ws.cell['E100'].number_format = '_ * #,##0_ ;_ * -#,##0_ ;_ * "-"??_ ;_ @_ '
openpyxl-1.7.0 에서는, 다음의 조작도 가능합니다.
cell.style.fill.start_color.index = "FF124191"
을 설정하는 기능을 몇 가지 .cell, 등 - 머리글 바닥글
공통 스타일을 정의한 후 모든 셀 또는 범위에 적용할 수 있습니다.
스타일 정의:
이것은 나에게 효과가 있었다(글씨 색 + 굵은 글꼴):
from openpyxl.styles import colors
from openpyxl.styles import Font, Color
from openpyxl import Workbook
wb = Workbook()
ws = wb['SheetName']
ws.cell(row_number,column_number).font = Font(color = "0000FF",bold = True)
언급URL : https://stackoverflow.com/questions/8440284/setting-styles-in-openpyxl
'programing' 카테고리의 다른 글
| 호출 필터가 반환됨 (0) | 2023.04.13 |
|---|---|
| Resharper가 설치되어 있는 Visual Studio에서는 키보드 단축키가 활성화되지 않습니다. (0) | 2023.04.13 |
| Python csv를 xlsx로 변환 (0) | 2023.04.13 |
| bash 명령어에 여러 env 변수를 설정하는 방법 (0) | 2023.04.13 |
| '치명적 오류:Optional value'의 래핑을 해제하는 동안 예기치 않게 0이 발견되었습니까? (0) | 2023.04.13 |

