Spaces:
Running
Running
Download script.js from CAGB058/xml-excel-data-explorer: direct link, hf CLI and curl.
- Browser
- Download file 20.4 kB
-
https://huggingface.co/spaces/CAGB058/xml-excel-data-explorer/resolve/main/script.js
- Command line
-
hf download hf://spaces/CAGB058/xml-excel-data-explorer/script.js
-
curl -L -o script.js https://huggingface.co/spaces/CAGB058/xml-excel-data-explorer/resolve/main/script.js
20.4 kB
| // Inicializar clipboard | |
| let clipboard = new ClipboardJS('.copy-btn'); | |
| clipboard.on('success', function(e) { | |
| showAlert("Copiado al portapapeles", "success"); | |
| e.clearSelection(); | |
| }); | |
| clipboard.on('error', function(e) { | |
| showAlert("Error al copiar", "error"); | |
| }); | |
| // Check saved theme preference | |
| const savedTheme = localStorage.getItem('theme') || 'light'; | |
| document.documentElement.setAttribute('data-theme', savedTheme); | |
| document.addEventListener('DOMContentLoaded', function() { | |
| const fileInput = document.getElementById('xmlFileInput'); | |
| const dashboard = document.getElementById('dashboard'); | |
| const saveBtn = document.getElementById('saveBtn'); | |
| const resetBtn = document.getElementById('resetBtn'); | |
| const expandAllBtn = document.getElementById('expandAllBtn'); | |
| const addRowBtn = document.getElementById('addRowBtn'); | |
| const exportExcelBtn = document.getElementById('exportExcelBtn'); | |
| const exportCsvBtn = document.getElementById('exportCsvBtn'); | |
| const exportJsonBtn = document.getElementById('exportJsonBtn'); | |
| const exportXmlBtn = document.getElementById('exportXmlBtn'); | |
| const dataExport = document.getElementById('dataExport'); | |
| // Variables globales para el estado | |
| let currentData = null; | |
| let originalData = null; | |
| let currentFileType = null; | |
| fileInput.addEventListener('change', handleFileSelect); | |
| saveBtn.addEventListener('click', saveChanges); | |
| resetBtn.addEventListener('click', resetData); | |
| expandAllBtn.addEventListener('click', expandAllNodes); | |
| addRowBtn.addEventListener('click', addNewRow); | |
| exportExcelBtn.addEventListener('click', () => exportData('xlsx')); | |
| exportCsvBtn.addEventListener('click', () => exportData('csv')); | |
| exportJsonBtn.addEventListener('click', () => exportData('json')); | |
| exportXmlBtn.addEventListener('click', () => exportData('xml')); | |
| function handleFileSelect(event) { | |
| const file = event.target.files[0]; | |
| if (!file) return; | |
| const fileExtension = file.name.split('.').pop().toLowerCase(); | |
| currentFileType = fileExtension; | |
| // Actualizar timestamp | |
| document.getElementById('timestamp').textContent = new Date().toLocaleString(); | |
| if (fileExtension === 'xml') { | |
| const reader = new FileReader(); | |
| reader.onload = function(e) { | |
| try { | |
| const parser = new DOMParser(); | |
| const xmlDoc = parser.parseFromString(e.target.result, "application/xml"); | |
| if (xmlDoc.getElementsByTagName("parsererror").length > 0) { | |
| showAlert("El archivo XML no es v谩lido. Por favor, verifica su formato.", "error"); | |
| return; | |
| } | |
| currentData = xmlDoc; | |
| originalData = xmlDoc.cloneNode(true); | |
| processXML(xmlDoc); | |
| showDashboard(); | |
| } catch (error) { | |
| console.error("Error parsing XML:", error); | |
| showAlert("Ocurri贸 un error al procesar el archivo XML.", "error"); | |
| } | |
| }; | |
| reader.readAsText(file); | |
| } else if (['xlsx', 'xls', 'csv'].includes(fileExtension)) { | |
| // Cargar SheetJS (xlsx) din谩micamente | |
| const script = document.createElement('script'); | |
| script.src = 'https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js'; | |
| script.onload = () => { | |
| const reader = new FileReader(); | |
| reader.onload = function(e) { | |
| try { | |
| const data = new Uint8Array(e.target.result); | |
| const workbook = XLSX.read(data, { type: 'array' }); | |
| // Procesar la primera hoja | |
| const firstSheetName = workbook.SheetNames[0]; | |
| const worksheet = workbook.Sheets[firstSheetName]; | |
| // Convertir a JSON | |
| const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 }); | |
| // Calcular m茅tricas | |
| const elementCount = jsonData.length - 1; // Excluyendo encabezados | |
| const attributeCount = jsonData[0] ? jsonData[0].length : 0; | |
| // Actualizar UI | |
| document.getElementById('elementCount').textContent = elementCount; | |
| document.getElementById('depthCount').textContent = 1; // Excel tiene solo 1 nivel | |
| document.getElementById('attributeCount').textContent = attributeCount; | |
| // Generar vista de 谩rbol | |
| const treeView = generateExcelTreeView(jsonData, firstSheetName); | |
| document.getElementById('xmlTree').innerHTML = treeView; | |
| // Generar tabla de datos | |
| generateExcelTable(jsonData, firstSheetName); | |
| dashboard.classList.remove('hidden'); | |
| } catch (error) { | |
| console.error("Error processing Excel file:", error); | |
| alert("Ocurri贸 un error al procesar el archivo Excel."); | |
| } | |
| }; | |
| reader.readAsArrayBuffer(file); | |
| }; | |
| document.head.appendChild(script); | |
| } else { | |
| alert("Formato de archivo no soportado. Por favor, sube un archivo XML o Excel."); | |
| } | |
| } | |
| function generateExcelTreeView(data, sheetName) { | |
| let html = `<span class="xml-tag">[Hoja: ${sheetName}]</span><br><br>`; | |
| // Encabezados | |
| html += '<span class="excel-sheet">Encabezados:</span><br>'; | |
| if (data[0]) { | |
| html += data[0].map(header => | |
| ` <span class="excel-cell">${header || '(vac铆o)'}</span><br>` | |
| ).join(''); | |
| } | |
| // Datos de ejemplo | |
| html += '<br><span class="excel-sheet">Datos (primeras 5 filas):</span><br>'; | |
| const sampleRows = data.slice(1, 6); | |
| sampleRows.forEach((row, i) => { | |
| html += ` <span class="xml-tag">[Fila ${i + 1}]</span><br>`; | |
| row.forEach((cell, j) => { | |
| const header = data[0] ? data[0][j] : `Col${j+1}`; | |
| html += ` <span class="excel-cell">${header}</span>: <span class="xml-value">${cell || '(vac铆o)'}</span><br>`; | |
| }); | |
| }); | |
| if (data.length > 6) { | |
| html += ` <span class="xml-value">... y ${data.length - 6} filas m谩s</span><br>`; | |
| } | |
| return html; | |
| } | |
| function generateExcelTable(data, sheetName) { | |
| const tableBody = document.getElementById('tableBody'); | |
| tableBody.innerHTML = ''; | |
| if (!data.length) return; | |
| const headers = data[0] || []; | |
| const rows = data.slice(1); | |
| // Limitar a 100 filas para no sobrecargar la UI | |
| const displayRows = rows.slice(0, 100); | |
| displayRows.forEach((row, rowIndex) => { | |
| row.forEach((cell, colIndex) => { | |
| const header = headers[colIndex] || `Col${colIndex+1}`; | |
| const rowNum = rowIndex + 2; // +1 para base 1, +1 porque saltamos encabezados | |
| const tr = document.createElement('tr'); | |
| tr.className = 'hover:bg-gray-50'; | |
| tr.innerHTML = ` | |
| <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${sheetName}!${header}${rowNum}</td> | |
| <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${cell || '(vac铆o)'}</td> | |
| `; | |
| tableBody.appendChild(tr); | |
| }); | |
| }); | |
| if (rows.length > 100) { | |
| const tr = document.createElement('tr'); | |
| tr.innerHTML = ` | |
| <td colspan="2" class="px-6 py-4 text-center text-sm text-gray-500"> | |
| Mostrando 100 de ${rows.length} filas | |
| </td> | |
| `; | |
| tableBody.appendChild(tr); | |
| } | |
| } | |
| function processXML(xmlDoc) { | |
| // Contar elementos | |
| const elements = xmlDoc.getElementsByTagName('*'); | |
| document.getElementById('elementCount').textContent = elements.length; | |
| // Analizar estructura y profundidad | |
| const root = xmlDoc.documentElement; | |
| const maxDepth = getMaxDepth(root); | |
| document.getElementById('depthCount').textContent = maxDepth; | |
| // Contar atributos | |
| let attributeCount = 0; | |
| const allElements = xmlDoc.getElementsByTagName('*'); | |
| for (let el of allElements) { | |
| attributeCount += el.attributes.length; | |
| } | |
| document.getElementById('attributeCount').textContent = attributeCount; | |
| // Generar vista de 谩rbol | |
| const treeView = generateTreeView(root); | |
| document.getElementById('xmlTree').innerHTML = treeView; | |
| // Generar tabla de datos | |
| generateDataTable(root); | |
| } | |
| function getMaxDepth(node, currentDepth = 1) { | |
| if (!node.children || node.children.length === 0) return currentDepth; | |
| let maxDepth = currentDepth; | |
| for (let child of node.children) { | |
| const depth = getMaxDepth(child, currentDepth + 1); | |
| if (depth > maxDepth) maxDepth = depth; | |
| } | |
| return maxDepth; | |
| } | |
| function generateTreeView(node, indent = 0) { | |
| let html = ''; | |
| const indentStr = ' '.repeat(indent * 4); | |
| // Abrir etiqueta | |
| html += `${indentStr}<span class="xml-tag"><${node.nodeName.toLowerCase()}</span>`; | |
| // Atributos | |
| if (node.attributes && node.attributes.length > 0) { | |
| for (let attr of node.attributes) { | |
| html += ` <span class="xml-attr">${attr.name}</span>=<span class="text-red-500">"${attr.value}"</span>`; | |
| } | |
| } | |
| html += '<span class="xml-tag">></span><br>'; | |
| // Contenido y nodos hijos | |
| if (node.childNodes.length > 0) { | |
| let hasElementChildren = false; | |
| for (let child of node.childNodes) { | |
| if (child.nodeType === Node.ELEMENT_NODE) { | |
| hasElementChildren = true; | |
| html += generateTreeView(child, indent + 1); | |
| } else if (child.nodeType === Node.TEXT_NODE && child.nodeValue.trim() !== '') { | |
| html += `${indentStr} <span class="xml-value">${child.nodeValue.trim()}</span><br>`; | |
| } | |
| } | |
| if (hasElementChildren) { | |
| html += `${indentStr}`; | |
| } | |
| } | |
| // Cerrar etiqueta | |
| html += `<span class="xml-tag"></${node.nodeName.toLowerCase()}></span><br>`; | |
| return html; | |
| } | |
| function generateDataTable(node) { | |
| const tableBody = document.getElementById('tableBody'); | |
| tableBody.innerHTML = ''; | |
| // Funci贸n recursiva para extraer datos | |
| function extractData(node, path = '') { | |
| const currentPath = path ? `${path}.${node.nodeName}` : node.nodeName; | |
| // Atributos | |
| if (node.attributes && node.attributes.length > 0) { | |
| for (let attr of node.attributes) { | |
| addRow(`${currentPath}@${attr.name}`, attr.value); | |
| } | |
| } | |
| // Contenido de texto | |
| let textContent = ''; | |
| for (let child of node.childNodes) { | |
| if (child.nodeType === Node.TEXT_NODE && child.nodeValue.trim() !== '') { | |
| textContent += child.nodeValue.trim(); | |
| } | |
| } | |
| if (textContent) { | |
| addRow(currentPath, textContent); | |
| } | |
| // Nodos hijos | |
| for (let child of node.childNodes) { | |
| if (child.nodeType === Node.ELEMENT_NODE) { | |
| extractData(child, currentPath); | |
| } | |
| } | |
| } | |
| function addRow(key, value) { | |
| const row = document.createElement('tr'); | |
| row.className = 'hover:bg-gray-50 group'; | |
| const keyCell = document.createElement('td'); | |
| keyCell.className = 'px-6 py-4 whitespace-nowrap text-sm text-gray-900'; | |
| keyCell.textContent = key; | |
| const valueCell = document.createElement('td'); | |
| valueCell.className = 'px-6 py-4 whitespace-nowrap'; | |
| const valueInput = document.createElement('input'); | |
| valueInput.type = 'text'; | |
| valueInput.className = 'w-full px-2 py-1 text-sm border border-gray-300 rounded focus:ring-primary focus:border-primary'; | |
| valueInput.value = value || ''; | |
| valueInput.addEventListener('change', () => { | |
| saveBtn.classList.remove('hidden'); | |
| resetBtn.classList.remove('hidden'); | |
| }); | |
| valueCell.appendChild(valueInput); | |
| const actionCell = document.createElement('td'); | |
| actionCell.className = 'px-2 py-4 whitespace-nowrap text-right text-sm font-medium opacity-0 group-hover:opacity-100 transition-opacity'; | |
| const deleteBtn = document.createElement('button'); | |
| deleteBtn.className = 'text-red-500 hover:text-red-700'; | |
| deleteBtn.innerHTML = '<i data-feather="trash-2" class="w-4 h-4"></i>'; | |
| deleteBtn.addEventListener('click', () => { | |
| row.remove(); | |
| saveBtn.classList.remove('hidden'); | |
| resetBtn.classList.remove('hidden'); | |
| }); | |
| actionCell.appendChild(deleteBtn); | |
| row.appendChild(keyCell); | |
| row.appendChild(valueCell); | |
| row.appendChild(actionCell); | |
| tableBody.appendChild(row); | |
| feather.replace(); | |
| } | |
| extractData(node); | |
| } | |
| function addNewRow() { | |
| const row = document.createElement('tr'); | |
| row.className = 'hover:bg-gray-50 group bg-blue-50'; | |
| const keyCell = document.createElement('td'); | |
| keyCell.className = 'px-6 py-4 whitespace-nowrap'; | |
| const keyInput = document.createElement('input'); | |
| keyInput.type = 'text'; | |
| keyInput.className = 'w-full px-2 py-1 text-sm border border-gray-300 rounded focus:ring-primary focus:border-primary'; | |
| keyInput.placeholder = 'Nueva clave'; | |
| keyCell.appendChild(keyInput); | |
| const valueCell = document.createElement('td'); | |
| valueCell.className = 'px-6 py-4 whitespace-nowrap'; | |
| const valueInput = document.createElement('input'); | |
| valueInput.type = 'text'; | |
| valueInput.className = 'w-full px-2 py-1 text-sm border border-gray-300 rounded focus:ring-primary focus:border-primary'; | |
| valueInput.placeholder = 'Nuevo valor'; | |
| valueCell.appendChild(valueInput); | |
| const actionCell = document.createElement('td'); | |
| actionCell.className = 'px-2 py-4 whitespace-nowrap text-right text-sm font-medium'; | |
| const confirmBtn = document.createElement('button'); | |
| confirmBtn.className = 'text-green-500 hover:text-green-700 mr-2'; | |
| confirmBtn.innerHTML = '<i data-feather="check" class="w-4 h-4"></i>'; | |
| confirmBtn.addEventListener('click', () => { | |
| if (!keyInput.value.trim()) { | |
| showAlert("Por favor ingresa una clave v谩lida", "warning"); | |
| return; | |
| } | |
| row.className = 'hover:bg-gray-50 group'; | |
| keyCell.innerHTML = keyInput.value; | |
| valueCell.innerHTML = `<input type="text" class="w-full px-2 py-1 text-sm border border-gray-300 rounded focus:ring-primary focus:border-primary" value="${valueInput.value}">`; | |
| actionCell.innerHTML = '<button class="text-red-500 hover:text-red-700"><i data-feather="trash-2" class="w-4 h-4"></i></button>'; | |
| saveBtn.classList.remove('hidden'); | |
| resetBtn.classList.remove('hidden'); | |
| feather.replace(); | |
| }); | |
| const cancelBtn = document.createElement('button'); | |
| cancelBtn.className = 'text-gray-500 hover:text-gray-700'; | |
| cancelBtn.innerHTML = '<i data-feather="x" class="w-4 h-4"></i>'; | |
| cancelBtn.addEventListener('click', () => row.remove()); | |
| actionCell.appendChild(confirmBtn); | |
| actionCell.appendChild(cancelBtn); | |
| row.appendChild(keyCell); | |
| row.appendChild(valueCell); | |
| row.appendChild(actionCell); | |
| tableBody.appendChild(row); | |
| feather.replace(); | |
| } | |
| function showDashboard() { | |
| dashboard.classList.remove('hidden'); | |
| dataExport.classList.remove('hidden'); | |
| feather.replace(); | |
| } | |
| function expandAllNodes() { | |
| // Implementar l贸gica para expandir todos los nodos del 谩rbol XML | |
| const tree = document.getElementById('xmlTree'); | |
| // Simulaci贸n de expansi贸n | |
| tree.querySelectorAll('.collapsible').forEach(node => { | |
| node.classList.remove('hidden'); | |
| }); | |
| } | |
| function saveChanges() { | |
| // Implementar l贸gica para guardar cambios | |
| showAlert("Cambios guardados correctamente", "success"); | |
| saveBtn.classList.add('hidden'); | |
| resetBtn.classList.add('hidden'); | |
| } | |
| function resetData() { | |
| if (confirm("驴Est谩s seguro de que deseas descartar todos los cambios?")) { | |
| if (currentFileType === 'xml') { | |
| processXML(originalData); | |
| } else { | |
| // Resetear datos Excel/CSV | |
| } | |
| saveBtn.classList.add('hidden'); | |
| resetBtn.classList.add('hidden'); | |
| showAlert("Cambios descartados", "info"); | |
| } | |
| } | |
| function exportData(format) { | |
| let fileName = 'exported_data'; | |
| let mimeType = ''; | |
| let data = ''; | |
| switch(format) { | |
| case 'xlsx': | |
| fileName += '.xlsx'; | |
| mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; | |
| // Implementar exportaci贸n a Excel | |
| break; | |
| case 'csv': | |
| fileName += '.csv'; | |
| mimeType = 'text/csv'; | |
| // Implementar exportaci贸n a CSV | |
| break; | |
| case 'json': | |
| fileName += '.json'; | |
| mimeType = 'application/json'; | |
| // Implementar exportaci贸n a JSON | |
| break; | |
| case 'xml': | |
| fileName += '.xml'; | |
| mimeType = 'application/xml'; | |
| // Implementar exportaci贸n a XML | |
| break; | |
| } | |
| const blob = new Blob([data], { type: mimeType }); | |
| const url = URL.createObjectURL(blob); | |
| const a = document.createElement('a'); | |
| a.href = url; | |
| a.download = fileName; | |
| document.body.appendChild(a); | |
| a.click(); | |
| document.body.removeChild(a); | |
| URL.revokeObjectURL(url); | |
| showAlert(`Datos exportados como ${format.toUpperCase()}`, "success"); | |
| } | |
| function showAlert(message, type) { | |
| // Implementar sistema de notificaciones | |
| console.log(`${type}: ${message}`); | |
| } | |
| }); |