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..)
- Horizontal lines start from A. Vertical lines start from "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
Create a new sheet:
Select the currently active sheet:
Select a sheet by name:
List of all sheet names:
Delete a sheet:
Cell
Select
Use the Sheet's cell function.
Select a Cell by Range.
Get multiple values by Range
Delete a 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')
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
- python
- python-pptx (PowerPoint)
- OpenPyXL (Excel)
- MS Office
- Neptyne - A spreadsheet programmable with AI and Python
Favorite site
Tutorials
Guide
Pages that link here