openpyxl-merged-cell-safe-write
하는 일
이 스킬은 openpyxl에서 병합 셀에 값을 쓰는 올바른 순서를 설명합니다. 여러 열에 걸친 제목이나 머리글이 있는 서식 스프레드시트를 만드는 사람에게 맞습니다.
사용하는 경우
- ✓병합된 제목이나 머리글이 있는 스프레드시트를 만들 때.
- ✓값을 쓰는 중 openpyxl에서 MergedCell 오류가 날 때.
- ✓여러 열에 걸친 제목을 깔끔한 서식으로 만들고 싶은 경우.
스킬 링크
https://github.com/HKUDS/AgentPilot/blob/main/openspace/benchmarks/gdpval/skills/openpyxl-merged-cell-safe-write/SKILL.md복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.
사용 방법
가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.
바로 붙여넣을 수 있는 메시지
Claude Code, Codex, Cursor용입니다. 프로젝트 폴더에서 실행하면 스킬이 설치됩니다.
SKILL.md를 다운로드해 에이전트의 스킬 폴더에 넣으세요.
AI에게 요청하는 예시
“네 개 열에 걸친 병합 제목이 있는 보고서를 만들어 주세요. 지난번에 제목 텍스트를 넣을 때 오류가 났으니 순서를 고쳐 주세요.”
매주 새 스킬 5개. 읽는 데 1분.
작동 방식
AI는 먼저 왼쪽 위 셀에 값을 쓰고, 그다음 범위를 병합하며, 이후 왼쪽 위 셀에 글꼴과 정렬을 적용합니다.
기술 내용 (원본 SKILL.md)
작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.
OpenPyXL Merged Cell Safe Write Pattern
Problem
When creating formatted spreadsheets with openpyxl, merging cells and then assigning values to them causes MergedCell errors. This is a common pitfall that can consume multiple failed iterations.
Core Rule
Always assign values to the top-left cell of a merge range BEFORE applying the merge, or avoid assigning to merged cells entirely after the merge is applied.
Correct Pattern
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
# CORRECT: Set value first, then merge
ws['A1'] = 'Quarterly Revenue Report' # Assign to top-left cell first
ws.merge_cells('A1:D1') # Then apply merge
# Also set formatting after merge
ws['A1'].font = Font(bold=True, size=16)
ws['A1'].alignment = Alignment(horizontal='center')
Incorrect Pattern (Causes MergedCell Error)
# WRONG: Merge first, then assign value
ws.merge_cells('A1:D1')
ws['A1'] = 'Quarterly Revenue Report' # This raises MergedCell error!
Step-by-Step Procedure
- Identify merge ranges you need for headers, titles, or grouped data
- Write values to the top-left cell of each range before merging
- Apply the merge using
ws.merge_cells() - Apply formatting (font, alignment, borders) to the top-left cell
- Verify by checking that only the top-left cell holds the value
Additional Guidelines
For Multiple Merged Regions
# Define all merges with their values
merges = [
('A1', 'D1', 'Quarterly Revenue Report'),
('A3', 'B3', 'Product'),
('C3', 'D3', 'Sales Data'),
]
for start_col, end_col, value in merges:
cell_ref = f'{start_col}' # Top-left cell
ws[cell_ref] = value # Set value first
ws.merge_cells(f'{start_col}:{end_col}') # Then merge
When Modifying Existing Merged Cells
If you need to update a value in an already-merged range:
# Get the top-left cell of the merged range
top_left = 'A1' # Know your merge structure
ws[top_left] = 'New Value' # Only modify the top-left cell
Checking for Merged Cells
# Check if a cell is within a merged range
def is_cell_merged(ws, cell_ref):
for merged_range in ws.merged_cells.ranges:
if cell_ref in merged_range:
return True
return False
# Or check before writing
if not is_cell_merged(ws, 'A1'):
ws['A1'] = 'Value'
ws.merge_cells('A1:D1')
Common Use Cases
| Use Case | Pattern |
|---|---|
| Title headers | Write to A1, then merge A1:D1 |
| Section headers | Write to first cell, then merge across columns |
| Grouped labels | Write to top-left, merge the group range |
| Centered content | Write, merge, then apply center alignment |
Quick Reference
# ✅ DO: Value → Merge → Format
ws['A1'] = 'Title'
ws.merge_cells('A1:E1')
ws['A1'].alignment = Alignment(horizontal='center')
# ❌ DON'T: Merge → Value
ws.merge_cells('A1:E1')
ws['A1'] = 'Title' # Error!
Testing Your Spreadsheet
After creation, verify merged cells work correctly:
# Save and reload to confirm no errors
wb.save('test.xlsx')
# Reload and check
wb2 = load_workbook('test.xlsx')
ws2 = wb2.active
print(ws2['A1'].value) # Should show the title value
자주 묻는 질문
MergedCell 오류는 무엇 때문에 생기나요?
병합을 적용한 뒤 값을 쓰면, openpyxl이 병합 블록의 일부로 보는 셀에 쓰게 되기 때문입니다.
어느 셀에 값을 넣나요?
병합 범위의 왼쪽 위 셀에만 값이 있어야 합니다.
서식은 어떻게 적용하나요?
병합 후 왼쪽 위 셀에 글꼴, 크기, 정렬을 설정합니다.
상세 정보
작성자의 원본 설명
Safe pattern for writing values to merged cells in openpyxl spreadsheets
repo: HKUDS/AgentPilot
인기도
- GitHub 스타
- 7.8k
- 순위
- #12901
- 라이선스
- MIT
- 업데이트
- 2026. 11. 1.
댓글
- …
이 저장소의 다른 스킬
agentpilot
7.8k작업을 준비하고 AgentPilot 루프를 실행해 변경을 제안, 테스트, 점수화하면서 프로젝트를 단계적으로 개선하도록 돕습니다.
openspace
7.8k에이전트 스킬을 저장하고 가져오는 도구인 OpenSpace를 설정하고, MCP를 통해 AI 앱에 연결하도록 돕습니다.
rsi-arena
7.8kAIME나 Terminal-Bench 같은 표준 AI 벤치마크 테스트를 설정하고 실행해 서로 다른 개선 방법을 비교하도록 돕습니다.
experiment-guide
7.8k프로그램을 개선하는 방법을 조사하면서 작은 실험을 계획하고, 결과를 읽고, 발견 사항을 기록하도록 돕습니다.
비슷한 스킬
feishu-doc
394k에이전트가 문서 도구를 사용해 텍스트, 이미지, 표를 포함한 Feishu 클라우드 문서를 읽고, 만들고, 편집하도록 돕습니다.
feishu-drive
394k에이전트가 봇과 공유된 Feishu 클라우드 폴더의 파일을 찾아보고, 정리하고, 댓글을 달도록 돕습니다.
feishu-perm
394k에이전트가 요청을 충족하는 가장 작은 권한을 골라, Feishu 파일에 누가 접근할 수 있는지 확인하고 바꾸도록 돕습니다.