달나라 노트

Python Pandas & openpyxl : fill (셀에 색상 채우기) 본문

Python/Python Pandas

Python Pandas & openpyxl : fill (셀에 색상 채우기)

CosmosProject 2024. 2. 26. 22:59
728x90
반응형

 

 

 

cell 객체의 fill 옵션을 조절하면 셀에 색상을 채울 수 있습니다.

 

import pandas as pd
from openpyxl.styles import PatternFill


dict_test = {
    'col1': [1, 2, 3, 4, 5],
    'col2': ['a', 'b', 'c', 'd', 'e'],
    'col3': [1234, 0.27383720, 39372, None, 102947291.293472],
    'col4': [0.9, 0.5238, 0.13, 0.0028, 1024.29278],
}

df_test = pd.DataFrame(dict_test)

xlsx_writer = pd.ExcelWriter('test.xlsx', engine='openpyxl')

df_test.to_excel(xlsx_writer, sheet_name='test', index=False)


worksheet = xlsx_writer.sheets['test']
cell = worksheet['B3']  # B3 cell의 객체를 가져옴

cell.fill = PatternFill(start_color='ffffd2d2', end_color='ffffd2d2', fill_type='solid')  # cell 객체에 색을 채움


xlsx_writer.close()

 

위 코드의 결과는 다음과 같습니다.

 

 

B3 cell에 원하는 색상이 채워진 것을 볼 수 있습니다.

 

Cell에 채울 색상을 의미하는 code는 ARGB code입니다.

 

 

 

 

 

 

GradientFill을 이용하면 아래 코드의 결과처럼 하나의 cell에 그라데이션으로 색을 채울 수도 있습니다.

 

import pandas as pd
from openpyxl.styles import GradientFill


dict_test = {
    'col1': [1, 2, 3, 4, 5],
    'col2': ['a', 'b', 'c', 'd', 'e'],
    'col3': [1234, 0.27383720, 39372, None, 102947291.293472],
    'col4': [0.9, 0.5238, 0.13, 0.0028, 1024.29278],
}

df_test = pd.DataFrame(dict_test)

xlsx_writer = pd.ExcelWriter('test.xlsx', engine='openpyxl')

df_test.to_excel(xlsx_writer, sheet_name='test', index=False)


worksheet = xlsx_writer.sheets['test']
cell = worksheet['B3']  # B3 cell의 객체를 가져옴

cell.fill = GradientFill(stop=('ffffd2d2', 'ffcfe3ff'))  # cell 객체에 색을 채움


xlsx_writer.close()

 

 

 

 

 

 

 

728x90
반응형
Comments