[Python] win32com (pywin32) 사용하기 (2) - 셀 꾸미기

Programming/PYTHON

[Python] win32com (pywin32) 사용하기 (2) - 셀 꾸미기

tnddj1219 2022. 2. 19. 12:14
728x90

Font 스타일 변경하기

ws.cells(1,1).Font.name = "굴림"

ws.cells(1,2).Font.Size = 14 

ws.cells(1,3).Font.Bold = True #굵게
ws.cells(1,3).Font.italic = True #글씨 기울기
ws.cells(1,3).Font.Underline = True #밑줄

글꼴, 글씨의 크기 등 다양하게 폰트 스타일을 변경할 수 있다. 

Font.Name, Font.SIze에 값을 넣어주면 글꼴, 폰트 크기를 변경하게 된다.

Fon.Bold, Font.Italic, Font.Underline을 True로 설정하여 다양한 글자 스타일을 적용할 수 있다. (False: 적용취소) 

 

코드 실행 결과

Font 색상 변경하기

## 방법1: ColorIndex 사용하기
ws.Cells(1,1).Font.ColorIndex=4

## 방법2: rgb->int로 변환하기
def rgbToInt(rgb):
   colorInt = rgb[0] + (rgb[1] * 256) + (rgb[2] * 256 * 256)
   return colorInt
ws.Cells(1, 2).Font.Color = rgbToInt((200, 130, 100))

글자에 색상을 넣는 방법은 두가지 방법이 있다.

첫번째는 Font.ColorIndex를 변경하는 방법이다. ColorIndex는 Microsoft에서 엑셀의 Color를 설정하는 고유의 설정을 말한다. 1~56까지 총 56가지의 색상을 지정할 수 있다.

 

ColorIndex 색상표

두번째는 Font.Color에 rgb값을 int로 변환하는 방법이다. 이 방법을 사용하면 ColorIndex보다 다양한 색깔을 설정할 수 있게 된다.

 

코드 실행 결과

Cell 색상 변경하기

## 방법1: ColorIndex 사용하기
ws.Cells(1,1).Interior.ColorIndex=7

## 방법2: rgb->int로 변환하기
def rgbToInt(rgb):
   colorInt = rgb[0] + (rgb[1] * 256) + (rgb[2] * 256 * 256)
   return colorInt
ws.Cells(1, 2).Interior.Color = rgbToInt((100, 130, 200))

셀 색상 변경은 Font 변경과 달리 Interior.Color / Interiror Color 속성 값을 변경하면 된다. (위의 내용 참고!)

 

코드 실행 결과

Cell 테두리 지정하기

ws.Range("B2").BorderAround(ColorIndex = 1,Weight = 2,LineStyle = 1)
ws.Range("B4").BorderAround(ColorIndex = 3,Weight = 3,LineStyle = 2)
ws.Range("C3").BorderAround(ColorIndex = 1,Weight = 4,LineStyle = 5)
ws.Range("C5").BorderAround(ColorIndex = 3,Weight = 4,LineStyle = 2)

BorderAround()함수를 사용하면 외곽 테두리를 지정해 줄 수 있다.

옵션으로 ColorIndex는 테두리 색, Wieght는 테두리 굵기, Linestyle은 선의 스타일을 지정하게된다.

 

코드 실행 결과

Cell 정렬하기

ws.Range("B1").VerticalAlignment = -4160  #위로 정렬
ws.Range("B1").HorizontalAlignment = -4108  #가운데 정렬(수평)

ws.Range("B3").VerticalAlignment = -4107  #아래로 정렬
ws.Range("B3").HorizontalAlignment = -4108  #가운데 정렬(수평)

ws.Range("A2").VerticalAlignment = -4108  #가운데 정렬(수직)
ws.Range("A2").HorizontalAlignment = -4131  #왼쪽으로 정렬

ws.Range("C2").VerticalAlignment = -4108  #가운데 정렬(수직)
ws.Range("C2").HorizontalAlignment = -4152  #오른쪽으로 정렬

ws.Range("B2").VerticalAlignment = -4108  #가운데 정렬(수직)
ws.Range("B2").HorizontalAlignment = -4108  #가운데 정렬(수평)

HorizotalAlignment는 수평방향에 대한 정렬을, VerticalAlignment는 수직 방향으로의 정렬을 말한다.

 

코드 실행 결과
VerticalAlignment 할 때 Value
HorizotalAlignment 할 때 Value

 

 

[출처] 사장님 몰래 하는 파이썬 업무자동화

728x90