Skip to content
Search

OpenPyXL

lastmod 2025-03-10created 2019-09-309 edits

A Python library to read/write Excel 2010 xlsx/xlsm files.

Terms

  • Workbook - A single Excel file
  • WorkSheet (=Sheet) - A single sheet tab at the bottom
  • Cell - A single box
  • Range - A range (e.g. A1:B10)
    • Horizontal lines start from A. Vertical lines start from "1". (Not 0, it's not 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

Create a new sheet:

ws = wb.create_sheet("new_sheet1")

Select the currently active sheet:

ws = wb.active

Select a sheet by name:

ws = wb["sheet3"]

List of all sheet names:

wss = wb.sheetnames

Delete a sheet:

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

Cell

Select

Use the Sheet's cell function.

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

Select a Cell by Range.

data = ws["B1"].value

Get multiple values by Range

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

Delete a range:

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')

Conditional formatting

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

author Zer0 sitemap