Skip to main content

Overview

Kontrak Backend accepts Excel files (.xlsx) containing employee data for bulk processing. The system validates headers, data types, and required fields before processing.

Excel File Requirements

File Format

  • Format: .xlsx (Excel 2007+)
  • Max size: 10MB (configurable)
  • Single or multiple sheets
  • UTF-8 encoding supported

Data Structure

  • Headers in row 1
  • Data starts from row 2
  • No merged cells in data area
  • Consistent data types per column

Required Column Headers

For Regular Contracts (PLANILLA, PART TIME)

The system recognizes multiple aliases for each field. Use any of the following:
FieldAccepted HeadersFormatExample
Namenombre, name, NOMBRE COMPLETOTextJuan
Father’s Last Nameapellido paterno, APELLIDO PATERNOTextPérez
Mother’s Last Nameapellido materno, APELLIDO MATERNOTextGarcía
DNIdni, DNI, Documento de identidad8 digits12345678
Emailemail, Email, correoEmail[email protected]
Birth DateFecha Nac., fecha de nacimientoDD/MM/YYYY15/03/1990
SexGENERO, genero, sexoM/FM
FieldAccepted HeadersFormatExample
Addressdirección, direccion, DOMICILIOTextAv. Principal 123
Provinceprovincia, PROVINCIATextLima
Districtdistrito, DISTRITOTextMiraflores
Departmentdepartamento, DEPARTAMENTOTextLima
FieldAccepted HeadersFormatExample
PositionCargo, CARGO, POSICIONTextAnalista
Salarysalario, sueldo, SUELDONumber3000
Salary in Wordssalario en letras, sueldo en letrasTexttres mil soles
Entry DateINICIO, fecha de ingresoDD/MM/YYYY01/01/2024
End DateFIN, FECHA DE TERMINO, Fecha FinDD/MM/YYYY31/12/2024
Subdivisionplaya, PLAYA, ESTACIONAMIENTOTextSede Central
Contract Typetipo de contrato, TIPO DE CONTRATOTextPlanilla

For SUBSIDIO Contracts

SUBSIDIO contracts require additional columns beyond the basic fields.
FieldAccepted HeadersFormatExample
Replacement ForSuplencia de:, SUPLENCIA DE, Reemplazo:TextCarlos Mendoza
Reason for SubstitutionMotivo de Suplencia, MOTIVO DE SUPLENCIATextVacaciones
Time For Companytiempo en empresa, Tiempo en EmpresaText6 meses
Working ConditionCONDICION LABORAL, condición laboralTextTemporal
Probationary PeriodPERIODO DE PRUEBA, Periodo de pruebaText3 meses

Upload Process

1

Prepare your Excel file

Ensure your Excel file has the correct headers and data format.
2

Upload the file

Send a POST request to /api/excel/upload with the Excel file:
curl -X POST http://localhost:3000/api/excel/upload \
  -F "[email protected]" \
  -H "Content-Type: multipart/form-data"
3

Receive validation results

The API responds with validated employee data or validation errors:Success Response:
{
  "success": true,
  "message": "Excel procesado correctamente",
  "data": {
    "employees": [
      {
        "name": "Juan",
        "lastNameFather": "Pérez",
        "lastNameMother": "García",
        "dni": "12345678",
        // ... other fields
      }
    ],
    "totalRecords": 10
  }
}

Data Type Handling

The Excel parser automatically handles various data formats:

Date Fields

Excel native date cells are automatically converted:
// Excel date object → DD/MM/YYYY string
const day = String(value.getUTCDate()).padStart(2, '0');
const month = String(value.getUTCMonth() + 1).padStart(2, '0');
const year = value.getUTCFullYear();
finalValue = `${day}/${month}/${year}`;
Supported Date Fields:
  • entryDate
  • endDate
  • birthDate

Numeric Fields

DNI can be entered as number or text, but must be 8 digits:
// Number → String conversion
if (field === 'dni' && typeof value === 'number') {
  finalValue = String(value);
}
✅ Valid: 12345678, 87654321
❌ Invalid: 1234567, 123456789, 12-345-678

Text Fields

Text fields are automatically trimmed and validated:
if (typeof value === 'string') {
  const trimmed = value.trim();
  return trimmed === '' ? null : trimmed;
}

Header Validation

The system performs strict header validation before processing data.

Validation Process

1

Extract headers

Headers are read from the first row (configurable) and normalized:
function normalizeHeader(header: string): string {
  return header
    .toLowerCase()
    .trim()
    .replace(/\s+/g, '')  // Remove spaces
    .normalize('NFD')
    .replace(/[\u0300-\u036f]/g, ''); // Remove accents
}
2

Map to fields

Each header is matched against known aliases:
for (const [field, config] of Object.entries(fields)) {
  const commonAlias = config.aliases.some(
    (alias) => normalizeHeader(alias) === normalized,
  );
  if (commonAlias) {
    return field;
  }
}
3

Check required fields

All required fields must be present:
const missingHeaders: string[] = [];
requiredField.forEach(([field, config]) => {
  if (!foundFields.has(field)) {
    const commonName = config.aliases[0];
    missingHeaders.push(commonName);
  }
});

Validation Errors

Missing Headers Error

If required headers are missing:
{
  "success": false,
  "message": "La estructura del archivo es incorrecta. Faltan columnas obligatorias.",
  "data": {
    "validationErrors": [
      {
        "row": 1,
        "field": "dni",
        "message": "Encabezado requerido no encontrado en el archivo."
      },
      {
        "row": 1,
        "field": "salario",
        "message": "Encabezado requerido no encontrado en el archivo."
      }
    ]
  }
}

Data Validation Errors

If data doesn’t meet validation rules:
{
  "success": false,
  "message": "No se pudo procesar el archivo. Se encontraron 3 errores.",
  "data": {
    "validationErrors": [
      {
        "row": 2,
        "field": "dni",
        "message": "DNI debe tener exactamente 8 dígitos numéricos."
      },
      {
        "row": 3,
        "field": "email",
        "message": "Invalid email"
      },
      {
        "row": 5,
        "field": "salary",
        "message": "El sueldo debe ser mayor a 0"
      }
    ]
  }
}

Advanced Options

The Excel parser supports additional configuration:
export interface ImportOptions {
  sheetIndex?: number;      // Índice de la hoja (0, 1, 2...)
  sheetName?: string;       // Nombre de la hoja
  skipEmptyRows?: boolean;  // Saltar filas vacías (default: true)
  skipEmptyCells?: boolean; // Saltar celdas vacías
  headerRow?: number;       // Número de fila donde están los encabezados (default: 1)
}

Processing Specific Sheets

// By sheet name
const options = {
  sheetName: 'Employees',
  headerRow: 1,
  skipEmptyRows: true
};

// By sheet index
const options = {
  sheetIndex: 0,  // First sheet
  headerRow: 1,
  skipEmptyRows: true
};

Example Excel Template

PLANILLA Template

nombreapellido paternoapellido maternodniemailFecha Nac.generodirecciónprovinciadistritodepartamentosueldosueldo en letrasCargoINICIOFINplayatipo de contrato
JuanPérezGarcía12345678[email protected]15/03/1990MAv. Principal 123LimaMirafloresLima3000tres mil solesAnalista01/01/202431/12/2024Sede CentralPlanilla

SUBSIDIO Template

nombreapellido paternoapellido maternodniemailFecha Nac.generodirecciónprovinciadistritodepartamentosueldosueldo en letrasCargoINICIOFINplayatipo de contratoSuplencia de:Motivo de Suplenciatiempo en empresaCONDICION LABORALPERIODO DE PRUEBA
MaríaLópezRuiz87654321[email protected]20/07/1988FJr. Los Olivos 456LimaSan IsidroLima2500dos mil quinientos solesAsistente15/02/202431/08/2024Oficina PrincipalSubsidioCarlos MendozaVacaciones6 mesesTemporal3 meses
Download the Excel templates from the examples above to ensure proper formatting.

Common Issues

Error: El archivo es demasiado grande. Tamaño máximo: 10 MBSolution:
  • Reduce file size by removing unnecessary formatting
  • Split data into multiple files
  • Increase MAX_FILE_SIZE in configuration
Error: El archivo Excel está corrupto o no es un archivo válidoSolution:
  • Save file as .xlsx format (not .xls)
  • Remove macros and VBA code
  • Open and re-save in Excel
Error: El archivo Excel no contiene datos válidosSolution:
  • Ensure data starts from row 2 (after headers)
  • Check for hidden rows/columns
  • Verify sheet is not empty
Error: Encabezado requerido no encontrado en el archivoSolution:
  • Check spelling of column headers
  • Use one of the accepted aliases
  • Remove extra spaces in headers
  • Ensure headers are in row 1

Best Practices

File Preparation

  • Use the latest Excel format (.xlsx)
  • Keep formatting simple
  • Avoid merged cells
  • Use consistent date formats
  • Remove empty rows between data

Data Entry

  • Use standard date format (DD/MM/YYYY)
  • Enter DNI without dashes or spaces
  • Use numeric format for salary
  • Verify email addresses
  • Double-check contract types

Validation

  • Test with small file first
  • Review validation errors carefully
  • Fix errors row by row
  • Keep backup of original file

Performance

  • Keep files under 5MB when possible
  • Limit to 1000 employees per file
  • Remove unnecessary columns
  • Use single sheet when possible

Next Steps

Generating Contracts

Generate contracts from uploaded data

Error Handling

Learn how to handle validation errors

Build docs developers (and LLMs) love