Trabajo con Excel en Swift (iOS/macOS): bibliotecas y ejemplos de código
El desarrollo de aplicaciones para iOS y macOS a menudo requiere integración con el formato Excel (.xlsx, .xls). Las herramientas nativas de Apple no proporcionan una API directa para trabajar con estos archivos, por lo que los desarrolladores utilizan bibliotecas de terceros. En este artículo, analizaremos tres opciones populares: CoreXLSX, xlsxwriter y SwiftCSV, y proporcionaremos ejemplos prácticos para leer y escribir datos.
1. CoreXLSX — lectura y escritura de .xlsx
CoreXLSX es una biblioteca de código abierto escrita completamente en Swift. Se basa en el formato interno ZIP (ya que .xlsx es un archivo ZIP con archivos XML). Admite lectura, escritura y edición de hojas, celdas y estilos.
Instalación: a través de Swift Package Manager (SPM), agregue el paquete https://github.com/CoreOffice/CoreXLSX.git.
Ejemplo: lectura de datos desde Excel
import CoreXLSX
func readExcelExample() { guard let filePath = Bundle.main.path(forResource: "data", ofType: "xlsx"), let data = try? Data(contentsOf: URL(fileURLWithPath: filePath)), let file = try? XLSXFile(data: data) else { print("No se pudo cargar el archivo") return } do { let sharedStrings = try file.parseSharedStrings() let worksheet = try file.parseWorksheet(at: "xl/worksheets/sheet1.xml") for row in worksheet.data?.rows ?? [] { var rowValues: [String] = [] for cell in row.cells { if let stringRef = cell.stringValue(sharedStrings) { rowValues.append(stringRef) } else if let value = cell.value { rowValues.append(value) } else { rowValues.append("") } } print(rowValues.joined(separator: ", ")) } } catch { print("Error de análisis: \\(error)") }}2. xlsxwriter — creación de archivos Excel en Swift
xlsxwriter es un envoltorio sobre la biblioteca libxlsxwriter (implementación en C). Permite crear archivos .xlsx con formato, fórmulas y gráficos. Ideal para generar informes en macOS e iOS.
Instalación: a través de CocoaPods (pod 'xlsxwriter') o SPM.
Ejemplo: creación de un archivo simple
import xlsxwriter
func createExcelExample() { let documentDirectory = FileManager.default.temporaryDirectory let fileURL = documentDirectory.appendingPathComponent("report.xlsx") let workbook = Workbook(path: fileURL.path) let sheet = workbook.addWorksheet(named: "Informe") // Encabezados sheet.writeString("Nombre", at: column: 0, row: 0) sheet.writeString("Edad", at: column: 1, row: 0) sheet.writeString("Ciudad", at: column: 2, row: 0) // Datos sheet.writeString("Ana", at: column: 0, row: 1) sheet.writeNumber(28, at: column: 1, row: 1) sheet.writeString("Moscú", at: column: 2, row: 1) sheet.writeString("Iván", at: column: 0, row: 2) sheet.writeNumber(35, at: column: 1, row: 2) sheet.writeString("San Petersburgo", at: column: 2, row: 2) workbook.close() print("Archivo creado: \\(fileURL)")}3. SwiftCSV — trabajo con CSV (alternativa a Excel)
Si no necesita el formato completo .xlsx, SwiftCSV es una biblioteca ligera para leer y escribir archivos CSV. CSV se abre fácilmente en Excel y otros editores de hojas de cálculo.
Instalación: a través de SPM: https://github.com/swiftcsv/SwiftCSV.git.
Ejemplo: lectura y escritura de CSV
import SwiftCSV
func csvExample() { // Lectura guard let csvURL = Bundle.main.url(forResource: "data", with