Saltar al contenido
Skillpedia
PDF, Word y diapositivas7,8 mil · #12877

excel-unmerge-before-write

Qué hace

Esta skill explica cómo tratar las celdas combinadas en una plantilla de Excel antes de rellenarla con datos mediante openpyxl. Está pensada para quienes rellenan formularios de hojas de cálculo ya preparados con automatización.

Cuándo usarla

  • ✓Cuando una plantilla de Excel tiene celdas combinadas donde necesito añadir valores.
  • ✓Cuando escribir en una celda da un error AttributeError.
  • ✓Cuando necesito rellenar datos en zonas de una plantilla que contienen rangos combinados.

Link de la skill

https://github.com/HKUDS/AgentPilot/blob/main/openspace/benchmarks/gdpval/skills/excel-unmerge-before-write/SKILL.md

Cópialo y pégalo en tu IA (Claude, ChatGPT o Cursor) pidiéndole que siga las instrucciones.

Cómo usar

La forma más fácil: copia el mensaje y pégalo en tu IA. Ella lee la skill y sigue las instrucciones.

Mensaje listo para pegar

Usa esta skill para ayudarme: https://github.com/HKUDS/AgentPilot/blob/main/openspace/benchmarks/gdpval/skills/excel-unmerge-before-write/SKILL.md Lee el archivo SKILL.md de ese link y sigue sus instrucciones en mi tarea.
¿Quieres que tu IA encuentre skills como esta por sí sola?Instala el MCP gratis de Skillpedia: una línea, y busca entre 15.000+ skills antes de cada tarea.Instalar en 1 minuto →

Ejemplo de qué pedirle a la IA

“Rellena mi plantilla de Excel con los datos del cliente, pero las celdas combinadas siguen dando errores. Arregla eso primero.”

5 skills nuevas por semana. 1 minuto de lectura.

Cómo funciona

La IA enumera los rangos combinados de la hoja, desfusiona los que están en la zona de escritura y después escribe cada valor en las celdas ya separadas antes de guardar.

Contenido técnico (SKILL.md original)

Texto original del autor, en inglés, directo de GitHub.

Excel Unmerge Before Write

When automating Excel file population with openpyxl, merged cells in templates can cause write failures. This skill provides the pattern to safely handle merged ranges before populating data.

When to Use

  • Working with Excel templates that have pre-existing merged cells
  • Getting AttributeError when trying to write values to certain cells
  • Needing to populate data in areas that may contain merged ranges

Core Pattern

Before writing values to cells in a worksheet, identify and unmerge any overlapping ranges:

from openpyxl import load_workbook

# Load the workbook
wb = load_workbook('template.xlsx')
ws = wb.active

# Unmerge specific ranges before writing
ws.unmerge_cells('A46:C46')
ws.unmerge_cells('E46:F46')
ws.unmerge_cells('I46:K46')

# Now safely write values
ws['A46'] = 'Value 1'
ws['E46'] = 'Value 2'
ws['I46'] = 'Value 3'

wb.save('output.xlsx')

Step-by-Step Instructions

  1. Identify merged ranges in your target worksheet:

    print(ws.merged_cells.ranges)
    
  2. Unmerge relevant ranges before writing any data to those areas:

    for merged_range in ws.merged_cells.ranges:
        # Optionally filter by area if you only need specific ranges
        ws.unmerge_cells(str(merged_range))
    
  3. Write your data to the now-unmerged cells:

    ws.cell(row=46, column=1, value='Your data')
    
  4. Save the workbook:

    wb.save('output.xlsx')
    

Handling Multiple Worksheets

If your workbook has multiple sheets with merged cells:

for sheet_name in wb.sheetnames:
    ws = wb[sheet_name]
    for merged_range in list(ws.merged_cells.ranges):
        ws.unmerge_cells(str(merged_range))

Common Errors

Error Cause Solution
AttributeError on cell write Writing to merged cell Call unmerge_cells() first
KeyError on range Invalid range string Use exact range format like 'A1:B2'
Data overwrites neighbors Unmerged too broadly Unmerge only needed ranges

Best Practices

  • Unmerge early: Call unmerge_cells() immediately after loading the worksheet, before any write operations
  • List before unmerging: Capture ws.merged_cells.ranges before unmerging if you need to know what was merged
  • Preserve formatting: If merge was for visual formatting, consider re-applying merges after data population if needed
  • Test ranges: Verify unmerged ranges don't break template layout expectations

Complete Example

from openpyxl import load_workbook

def populate_excel_template(template_path, output_path, data_dict):
    """Populate an Excel template, handling merged cells safely."""
    wb = load_workbook(template_path)
    ws = wb.active
    
    # Unmerge all cells that might conflict with data writes
    for merged_range in list(ws.merged_cells.ranges):
        ws.unmerge_cells(str(merged_range))
    
    # Populate data
    for cell_ref, value in data_dict.items():
        ws[cell_ref] = value
    
    wb.save(output_path)
    return output_path
Preguntas frecuentes

¿Qué causa el error?

Escribir en una celda combinada puede fallar en openpyxl, así que primero hay que quitar la combinación.

¿Puedo desfusionar solo algunos rangos?

Sí. La guía indica que se pueden desfusionar solo los rangos concretos que se necesitan.

¿Sobrescribe la plantilla?

El ejemplo guarda el libro rellenado con un nombre de archivo nuevo.

Detalles

Descripción original del autor

Unmerge merged cells in openpyxl worksheets before writing values to avoid AttributeError

repo: HKUDS/AgentPilot

Popularidad

Estrellas en GitHub
7,8 mil
Posición en el ranking
#12877
Licencia
MIT
Actualizada
1/11/2026

¿Te sirve esta skill?

0

Entra para votar.

Comentarios

  • …

Más skills de este repositorio

Skills parecidas