Trabajo con Excel en Swift en iOS y macOS: bibliotecas y ejemplos de código

Entrenador de Python en Línea para Principiantes

Aprende Python fácilmente sin sobrecargarte de teoría. Resuelve tareas prácticas con verificación automática, recibe pistas y escribe código directamente en el navegador, sin instalar nada.

Start Course

Trabajo con Excel en Swift: bibliotecas y herramientas para iOS y macOS



Al desarrollar aplicaciones para iOS y macOS, a menudo surge la necesidad de importar, exportar o procesar datos en formato Excel (XLSX, CSV). En la plataforma Apple no hay soporte integrado para formatos Excel, por lo que los desarrolladores utilizan bibliotecas de terceros. En este artículo analizaremos tres herramientas populares: CoreXLSX, XLSXWriter y SwiftCSV, y también proporcionaremos ejemplos prácticos de código en Swift.



1. CoreXLSX — lectura y escritura de XLSX



CoreXLSX es una biblioteca ligera para leer y crear archivos XLSX. Está basada en el estándar Open XML, y admite cadenas, números, fechas, fórmulas y estilos.



Instalación

// Swift Package Managerdependencies: [    .package(url: "https://github.com/CoreOffice/CoreXLSX.git", from: "0.14.0")]


Ejemplo: lectura de datos desde Excel

import CoreXLSX

func readExcel(path: String) { guard let file = XLSXFile(filepath: path) else { print("Error al abrir el archivo") return } do { for path in try file.parseWorksheetPaths() { let worksheet = try file.parseWorksheet(at: path) let rows = worksheet.data?.rows ?? [] for row in rows { let values = row.cells.compactMap { $0.value } print(values.joined(separator: "\\t")) } } } catch { print("Error de lectura: \\(error)") }}


Ejemplo: creación de un nuevo archivo XLSX

import CoreXLSX

func createExcel() { let header = ["Nombre", "Edad", "Ciudad"] let data = [ ["Ana", "25", "Moscú"], ["Boris", "30", "San Petersburgo"] ] var sharedStrings = SharedStrings() let headerRefs = header.map { sharedStrings.append(string: $0) } let dataRefs = data.map { row in row.map { sharedStrings.append(string: $0) } } let headerRow = Row(cells: headerRefs.enumerated().map { (index, ref) in Cell(reference: "\\(Character(UnicodeScalar(65 + index)!))1", type: .string, value: ref) }) let dataRows = dataRefs.enumerated().map { (rowIndex, row) in Row(cells: row.enumerated().map { (colIndex, ref) in let colRef = Character(UnicodeScalar(65 + colIndex)!) return Cell(reference: "\\(colRef)\\(rowIndex + 2)", type: .string, value: ref) }) } let worksheet = Worksheet(data: Data(rows: [headerRow] + dataRows)) let file = XLSXFile(sharedStrings: sharedStrings, worksheets: [worksheet]) do { try file.write(to: URL(fileURLWithPath: "/tmp/example.xlsx")) print("Archivo guardado") } catch { print("Error de escritura: \\(error)") }}


2. XLSXWriter — escritura rápida de archivos grandes



XLSXWriter es una biblioteca orientada al rendimiento en la escritura. Es adecuada para exportar miles de filas, y admite estilos, combinación de celdas y gráficos.



Instalación

// A través de CocoaPodspod 'XLSXWriter'


Ejemplo: escritura de datos con formato

import XLSXWriter

func writeFormattedExcel() { let workbook = Workbook() let sheet = workbook.addSheet(named: "Informe") // Estilos let headerStyle = CellStyle() headerStyle.font = Font(name: "Helvetica", size: 14, bold: true) headerStyle.fill = Fill(color: .lightGray) let dataStyle = CellStyle() dataStyle.font = Font(name: "Helvetica", size: 12) dataStyle.border = Border(top: .thin, bottom: .thin) // Encabezados sheet.write(row: 0, column: 0, value: "Producto", style: headerStyle) sheet.write(row: 0, column: 1, value: "Precio", style: headerStyle) sheet.write(row: 0, column: 2, value: "Cantid

Recommendations