Skip to content

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 이랑은..)

Install

pip install openpyxl

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")
import openpyxl as op
wb = op.load_workbook("test.xlsx")

Sheet

새로운 시트 생성:

ws = wb.create_sheet("new_sheet1")

현재 활성화된 시트 선택:

ws = wb.active

특정 이름의 시트 선택:

ws = wb["sheet3"]

전체 시트 이름 목록:

wss = wb.sheetnames

시트 삭제:

ws = wb.create_sheet("new_sheet1")
wb.remove(ws)

Cell

Select

Sheet의 cell 함수 사용.

data = ws.cell(row=1, column=2).value

Range로 Cell 선택.

data = ws["B1"].value

Range로 여러 데이터 획득

rows = ws["A1:C3"]  # A1:C3 범위 저장 (총 9개 Cell)
for row in rows:
    for cell in row:
        print(cell.value)

범위 삭제:

Worksheet.delete_rows(index, size)
Worksheet.delete_cols(index, size)

Insert image

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

Favorite site

Tutorials

Guide