OpenPyXL
A Python library to read/write Excel 2010 xlsx/xlsm files.
Terms
- Workbook - 엑셀 파일 하나
- WorkSheet (=Sheet) - 하단의 시트 탭 하나
- Cell - 네모칸 하나
- Range - 범위 (e.g.
A1:B10
)- 가로줄은 A 부터 시작. 세로줄은 "1" 부터 시작. (
0 이랑은 다르다 0 이랑은..)
- 가로줄은 A 부터 시작. 세로줄은 "1" 부터 시작. (
Install
Save and Load
import openpyxl as op
wb = op.Workbook()
ws = wb.create_sheet("new_sheet1") # New Seet
# OR
ws = wb.active # Activated sheet
wb.save("test.xlsx")
Sheet
새로운 시트 생성:
현재 활성화된 시트 선택:
특정 이름의 시트 선택:
전체 시트 이름 목록:
시트 삭제:
Cell
Select
Sheet의 cell
함수 사용.
Range로 Cell 선택.
Range로 여러 데이터 획득
범위 삭제:
Insert image
- Stackoverflow - how to change size of picture using openpyxl
- Stackoverflow - Insert image in openpyxl
import openpyxl
wb = openpyxl.Workbook()
ws = wb.worksheets[0]
img = openpyxl.drawing.image.Image('test.jpg')
img.anchor = 'A1'
img.width = 300
img.height = 300
ws.add_image(img)
wb.save('out.xlsx')
Background color
import openpyxl
wb = openpyxl.Workbook()
ws = wb.worksheets[0]
ws['A1'].fill = openpyxl.styles.PatternFill(start_color=hex_color, end_color=hex_color, fill_type="solid")
wb.save('out.xlsx')
조건부 서식
from openpyxl import Workbook
from openpyxl.formatting.rule import CellIsRule
from openpyxl.styles import PatternFill
# 새로운 엑셀 파일 생성
workbook = Workbook()
sheet = workbook.active
# 샘플 데이터 추가
data = [
[1, 2, 3],
[4, 1, 6],
[7, 8, 1]
]
for row in data:
sheet.append(row)
# 조건부 서식을 위한 노란색 Fill 스타일 정의
yellow_fill = PatternFill(start_color="FFFF00", end_color="FFFF00", fill_type="solid")
# 조건부 서식 규칙 생성 (셀 값이 1일 때)
rule = CellIsRule(operator="equal", formula=["1"], stopIfTrue=True, fill=yellow_fill)
# 범위에 조건부 서식 적용 (예: A1:C3)
sheet.conditional_formatting.add("A1:C3", rule)
# 파일 저장
workbook.save("conditional_formatting_example.xlsx")
See also
- python
- python-pptx (PowerPoint)
- OpenPyXL (Excel)
- MS Office
- Neptyne - AI와 파이썬으로 프로그래밍 가능한 스프레드시트