Insert data from Excel/CSV

VerifiedSafe

Read an Excel (.xlsx) or CSV (.csv) file and bulk load data into the PostgreSQL database of the Casas Comunales project. Handles column mapping, duplicate validation, and error reporting.

Sby Skills Guide Bot
Data & AIIntermediate
7/24/2026
Claude Code
#excel-import#csv-import#postgresql#data-validation#bulk-insert

Recommended for

Automated summary

Reads an Excel (.xlsx) or CSV (.csv) file and bulk-inserts the data into the Casas Comunales PostgreSQL database, with column mapping, duplicate validation, and error reporting.

Strengths

  • Automates importing data from common file formats (Excel, CSV).
  • Validates data before insertion to minimize errors.
  • Handles duplicates and required fields with clear reporting.
  • Inserts row by row so one failure doesn't block others.

Limitations

  • Requires the user to provide a file with a compatible structure.
  • Only handles specific project tables (participants, houses, etc.).
  • Depends on pandas and openpyxl, which must be installed.
When to use it

Use this skill when you need to import an Excel or CSV file containing structured data (participants, houses, workshops) into the Casas Comunales project database.

When not to use it

Do not use it for non-tabular files, single-row imports, or if the file contains unstructured data like free text.

Security analysis

Safe
Quality score90/100

The skill performs legitimate database insertion operations with proper validation and user confirmation. It uses bash and Python for data processing and database connectivity, but no destructive or exfiltration actions are present. Credentials are read from a local .env file, which is standard.

No concerns found

How this analysis is made

Examples

Excel de participantes
Te paso un Excel con los datos de los participantes para cargar a la base de datos del proyecto Casas Comunales. El archivo está en C:\Users\KEVIN\Desktop\participantes.xlsx.
CSV de talleres
Tengo un archivo CSV con la lista de talleres. Quiero insertar esos datos masivamente en la tabla talleres del proyecto. La ruta es C:\data\talleres.csv.
Migración desde otro sistema
Necesito migrar los datos de casas comunales desde un Excel que generó el sistema antiguo. ¿Puedes cargarlos? El archivo está en C:\migracion\casas.xlsx.

name: insertar-excel description: Lee un archivo Excel (.xlsx) o CSV (.csv) y carga los datos masivamente a la base de datos PostgreSQL del proyecto Casas Comunales. Úsalo cuando el usuario diga "te paso un Excel", "tengo un archivo con datos", "quiero cargar datos masivos", "inserta desde Excel/CSV", "tengo una lista de participantes/casas/talleres en una hoja de cálculo", o cuando comparta una ruta a un archivo de datos. También úsalo cuando el usuario migre datos de otro sistema. Maneja automáticamente el mapeo de columnas, validaciones de duplicados y reporte de errores.

Insertar datos desde Excel/CSV — Casas Comunales

El proyecto está en c:\Users\KEVIN\Desktop\casas comunales. Credenciales de BD en .env.

El objetivo es hacer la carga de datos lo más segura posible: mostrar al usuario qué se encontró, validar antes de tocar la BD, e insertar solo lo que es válido.

Paso 1 — Verificar pandas

python -c "import pandas; import openpyxl; print('OK')"

Si falla: pip install pandas openpyxl

Paso 2 — Obtener información del usuario

Si el usuario no lo dijo, preguntar en un solo mensaje:

  1. ¿Ruta del archivo? (ej: C:/Users/KEVIN/Desktop/datos.xlsx)
  2. ¿Qué tipo de datos trae? (participantes / casas comunales / talleres / usuarios)

Si ya lo dijo, continuar directamente.

Paso 3 — Leer y previsualizar

import pandas as pd

ruta = "ruta/del/archivo"
df = pd.read_csv(ruta) if ruta.lower().endswith(".csv") else pd.read_excel(ruta)

# Limpiar nombres de columnas (espacios, mayúsculas)
df.columns = df.columns.str.strip()

print(f"Total filas: {len(df)}")
print(f"Columnas encontradas: {df.columns.tolist()}")
print(df.head(3).to_string())

Mostrar al usuario las columnas reales del archivo y proponer el mapeo. Confirmar antes de insertar.

Paso 4 — Mapeos de referencia

Ajustar según las columnas reales del archivo. Estos son los mapeos más comunes:

Participantes → tabla participantes | Columna Excel (posibles nombres) | Campo BD | |----------------------------------|----------| | Nombres, Nombre, NOMBRE | nombres (obligatorio) | | Apellidos, Apellido | apellidos (obligatorio) | | CI, Cédula, Cedula, C.I. | ci (obligatorio, único) | | Fecha Nac, FechaNacimiento, F. Nacimiento | fecha_nacimiento | | Género, Genero, Sexo | genero → normalizar a M/F/O | | Teléfono, Telefono, Cel | telefono | | Casa, Casa Comunal, CasaID | casa_comunal_id |

Casas Comunales → tabla casas_comunales | Columna Excel | Campo BD | |---------------|----------| | Nombre, Casa | nombre (obligatorio) | | Dirección, Direccion | direccion (obligatorio) | | Macrodistrito, Distrito | macrodistrito (obligatorio) | | Representante | representante_nombre | | Teléfono, Contacto | contacto_telefono |

Paso 5 — Validar antes de insertar

Usar el script de validación para no sorprender al usuario:

import psycopg2, os
from dotenv import load_dotenv
load_dotenv()

conn = psycopg2.connect(os.getenv("DATABASE_URL"))
cur = conn.cursor()

duplicados = []
nulos = []

for idx, row in df.iterrows():
    fila = idx + 2  # +2 porque idx empieza en 0 y hay cabecera
    
    # Verificar campos obligatorios
    if pd.isna(row.get("ci")) or str(row.get("ci", "")).strip() == "":
        nulos.append(f"Fila {fila}: CI vacía")
        continue
    
    # Verificar duplicados en BD
    cur.execute("SELECT id FROM participantes WHERE ci = %s", (str(row["ci"]).strip(),))
    if cur.fetchone():
        duplicados.append(f"Fila {fila}: CI {row['ci']} ya existe en BD")

conn.close()
print(f"Filas válidas para insertar: {len(df) - len(duplicados) - len(nulos)}")
print(f"Duplicados: {len(duplicados)}")
print(f"Nulos en campos obligatorios: {len(nulos)}")

Reportar al usuario y pedir confirmación para continuar.

Paso 6 — Insertar (solo los válidos)

Insertar fila por fila con manejo de errores individuales. Una fila que falla no cancela las demás:

insertados = 0
fallidos = []

for idx, row in df_validos.iterrows():
    try:
        cur.execute("""
            INSERT INTO participantes (nombres, apellidos, ci, genero, telefono, casa_comunal_id)
            VALUES (%s, %s, %s, %s, %s, %s)
        """, (
            str(row["nombres"]).strip(),
            str(row["apellidos"]).strip(),
            str(row["ci"]).strip(),
            str(row.get("genero", "")).strip().upper()[:1] or None,
            str(row.get("telefono", "")).strip() or None,
            int(row["casa_comunal_id"]) if pd.notna(row.get("casa_comunal_id")) else None,
        ))
        insertados += 1
    except Exception as e:
        conn.rollback()
        fallidos.append(f"Fila {idx+2}: {str(e)[:80]}")
    else:
        conn.commit()

cur.close()
conn.close()

Paso 7 — Reporte final

📊 RESULTADO DE INSERCIÓN
─────────────────────────
✅ Insertados correctamente:  N
⚠️  Omitidos (ya existían):   N
❌ Errores al insertar:       N

Detalle de errores (si hay):
  - Fila 5: valor de fecha_nacimiento inválido
  - Fila 12: casa_comunal_id 99 no existe

From the file to a first result

The download contains exactly the content displayed on this page. This copy may differ from the latest version in the source repository.

View the source and supporting files

This download contains SKILL.md only. Any scripts, references, templates and dependencies are not included. Get the required files from the source, preserving their directory structure, before continuing.

1. Download the file

Download SKILL.md

From the root of a test project, save the file as .skill-downloads/insert-data-from-excel-csv-mryiqit0/SKILL.md, or use the command below. This folder is for inspecting the skill before installation.

Command for macOS/Linux or WSL: requires a POSIX shell and curl. On Windows without WSL, use the download button and create the folder manually.

mkdir -p '.skill-downloads/insert-data-from-excel-csv-mryiqit0' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/insert-data-from-excel-csv-mryiqit0/download' --output '.skill-downloads/insert-data-from-excel-csv-mryiqit0/SKILL.md.part' && mv '.skill-downloads/insert-data-from-excel-csv-mryiqit0/SKILL.md.part' '.skill-downloads/insert-data-from-excel-csv-mryiqit0/SKILL.md'

2. Check prerequisites

Read SKILL.md before using it. If it references scripts or external services, inspect them and prepare the required access in your test environment.

No recognized prerequisites section in this file. This does not mean it is self-contained: libraries, tools and access requirements may be mentioned elsewhere in the content or source repository.

The platforms on this page are catalog indications. The paths below follow tool documentation; they do not prove this skill has been run in those tools. No minimum tool version is confirmed for this listing.

3. Load the skill

After inspection, copy the complete folder into your project using one of the commands below, then open a new tool session. The command stops if a folder with the same name already exists: compare the files before replacing it.

Claude Code
test -f '.skill-downloads/insert-data-from-excel-csv-mryiqit0/SKILL.md' && test -s '.skill-downloads/insert-data-from-excel-csv-mryiqit0/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/insertar-excel' && cp -R '.skill-downloads/insert-data-from-excel-csv-mryiqit0' '.claude/skills/insertar-excel'

OpenSkills

OpenSkills must already be installed. The local install/read procedure is checked with OpenSkills 1.5.0, which requires Node.js ≥ 20.6.0. Catalog slugs are not resolved automatically.

Official OpenSkills installation
openskills install './.skill-downloads/insert-data-from-excel-csv-mryiqit0'

openskills read 'insert-data-from-excel-csv-mryiqit0'

Reading should display the installed file content and its base directory. It does not run the skill or install its dependencies.

For an agent that reads AGENTS.md, then sync the index. This command changes AGENTS.md: review the diff before using it.

openskills sync

Manual method or another tool: attach SKILL.md to a conversation, or open it in an agent that can read files. Include any required supporting resources. No universal folder is recognized by every tool.

4. Try a first task

Use a short, synthetic input: an API endpoint, a small document or an interface brief. In a new conversation, attach the file or give the agent its path, then adapt this request:

Read .skill-downloads/insert-data-from-excel-csv-mryiqit0/SKILL.md and apply its instructions to this example: [describe a test input]. Identify any missing files, dependencies or access. Produce the result requested by the skill without inventing data or running unreviewed scripts.

Expected result: output matching the skill instructions, or a precise list of missing prerequisites. A read confirmation alone does not validate a first use. If an external resource is unavailable, that path remains untested.

Related skills