### Path Example Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/comments-and-relationships.md Example usage of the Path type. ```swift let path1 = Path("xl/worksheets/sheet1.xml") print("Value: \(path1.value)") // xl/worksheets/sheet1.xml print("Is root: \(path1.isRoot)") // false print("Components: \(path1.components)") // ["xl", "worksheets", "sheet1.xml"] let path2 = Path("/xl/styles.xml") print("Value: \(path2.value)") // /xl/styles.xml print("Is root: \(path2.isRoot)") // true print("Components: \(path2.components)") // ["xl", "styles.xml"] ``` -------------------------------- ### Workbook.Sheet Example Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/workbook.md Example of parsing worksheet paths and names. ```swift let workbooks = try file.parseWorkbooks() for workbook in workbooks { let wsInfo = try file.parseWorksheetPathsAndNames(workbook: workbook) for (name, path) in wsInfo { let sheetName = name ?? "Unnamed" print("Sheet: \(sheetName) at \(path)") } } ``` -------------------------------- ### bufferSize Configuration Example Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/configuration.md Examples demonstrating how to adjust the bufferSize for very large files or memory-constrained environments. ```swift // For very large files (100+ MB) let file = XLSXFile( filepath: filepath, bufferSize: 100 * 1024 * 1024 // 100 MB ) // For memory-constrained environments let file = XLSXFile( filepath: filepath, bufferSize: 1 * 1024 * 1024 // 1 MB ) ``` -------------------------------- ### Columns Example Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/worksheet.md Example of accessing column formatting information. ```swift if let columns = worksheet.columns { for col in columns.items { print("Columns \(col.min)-\(col.max): width \(col.width)") } } ``` -------------------------------- ### Column Example Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/worksheet.md Example of iterating through column ranges and their widths. ```swift if let columns = worksheet.columns { for col in columns.items { let colRange = "\(col.min)-\(col.max)" print("Column range \(colRange): width \(col.width)") } } ``` -------------------------------- ### Workbook.View Example Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/workbook.md Example of accessing and printing workbook view information. ```swift let workbooks = try file.parseWorkbooks() if let views = workbooks.first?.views { for view in views.items { print("Window: (\(view.xWindow ?? 0), \(view.yWindow ?? 0))") print("Size: \(view.windowWidth ?? 800) x \(view.windowHeight ?? 600)") } } ``` -------------------------------- ### errorContextLength Configuration Example Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/configuration.md Examples showing how to set errorContextLength for debugging corrupted XLSX files and for production code. ```swift // For debugging let file = try XLSXFile( data: fileData, errorContextLength: 20 ) do { let worksheet = try file.parseWorksheet(at: path) } catch { // Error message now includes surrounding XML context print(error) } // Production code let file = XLSXFile( filepath: filepath, errorContextLength: 0 // Smaller error messages ) ``` -------------------------------- ### watchOS Buffer Size Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/configuration.md Example of setting a minimal buffer size for watchOS. ```swift #if os(watchOS) let bufferSize: UInt32 = 2 * 1024 * 1024 // 2 MB on watchOS #else let bufferSize: UInt32 = 10 * 1024 * 1024 #endif ``` -------------------------------- ### Worksheet.Data Example Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/worksheet.md Example of getting the row count of a worksheet. ```swift let worksheet = try file.parseWorksheet(at: path) let rowCount = worksheet.data?.rows.count ?? 0 print("Worksheet has \(rowCount) non-empty rows") ``` -------------------------------- ### No-Configuration Parsing Example Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/configuration.md Demonstrates the default, zero-configuration usage of CoreXLSX for typical XLSX files. ```swift // This just works for most XLSX files guard let file = XLSXFile(filepath: path) else { return } let workbooks = try file.parseWorkbooks() let paths = try file.parseWorksheetPaths() let worksheet = try file.parseWorksheet(at: paths[0]) ``` -------------------------------- ### Workbook.Sheets Example Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/workbook.md Example of accessing sheet items from the Sheets container. ```swift let workbooks = try file.parseWorkbooks() let sheets = workbooks.first?.sheets.items ?? [] for sheet in sheets { print("Sheet: \(sheet.name ?? \"unnamed\")") } ``` -------------------------------- ### Get comments for each worksheet Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/comments-and-relationships.md Example of how to retrieve and print comments for each worksheet. ```swift // Get comments for each worksheet let paths = try file.parseWorksheetPaths() for path in paths { let comments = try file.parseComments(forWorksheet: path) for (cellRef, comment) in comments.commentList.itemsByReference { print("Comment at \(cellRef): \(comment.text.plain ?? "")") } } ``` -------------------------------- ### Example Usage of Comment Type Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/comments-and-relationships.md Example demonstrating how to access the reference and text of a comment. ```swift for comment in comments.commentList.items { print("Cell \(comment.reference)") print("Text: \(comment.text.plain ?? "")") } ``` -------------------------------- ### Color Example Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/styles.md Example of how to access and print color properties. ```swift if let color = font.color { if let rgb = color.rgb { print("RGB: \(rgb)") } else if let idx = color.indexed { print("Indexed color: \(idx)") } } ``` -------------------------------- ### Workbook Example Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/workbook.md Example of iterating through sheets in a parsed workbook. ```swift let workbooks = try file.parseWorkbooks() for workbook in workbooks { print("Workbook has \(workbook.sheets.items.count) sheets:") for sheet in workbook.sheets.items { print(" - \(sheet.name ?? \"Unnamed\") (ID: \(sheet.id))") } } ``` -------------------------------- ### iOS Buffer Size Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/configuration.md Example of setting a smaller buffer size for iOS devices due to memory constraints. ```swift #if os(iOS) let bufferSize: UInt32 = 5 * 1024 * 1024 // 5 MB on iOS #else let bufferSize: UInt32 = 10 * 1024 * 1024 // 10 MB elsewhere #endif let file = XLSXFile(filepath: filepath, bufferSize: bufferSize) ``` -------------------------------- ### NumberFormat Example Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/styles.md Example of iterating through custom number formats. ```swift let styles = try file.parseStyles() if let numFormats = styles.numberFormats { for fmt in numFormats.items { print("ID \(fmt.id): \(fmt.formatCode)") } } ``` -------------------------------- ### Development Workflow Setup Source: https://github.com/coreoffice/corexlsx/blob/main/README.md Commands to set up the development environment on macOS using Homebrew, SwiftLint, SwiftFormat, and pre-commit hooks. ```shell brew bundle # installs SwiftLint, SwiftFormat and pre-commit pre-commit install # installs pre-commit hook to run checks before you commit ``` -------------------------------- ### InlineString Example Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/worksheet.md Example of how to access inline string content from a cell. ```swift let cell = worksheet.data?.rows.first?.cells.first if let inlineStr = cell?.inlineString { print("Inline string: \(inlineStr.text ?? \"")") } ``` -------------------------------- ### Server Application Buffer Size Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/configuration.md Example of increasing buffer size for server applications processing very large files. ```swift // Server application let file = XLSXFile( filepath: filepath, bufferSize: 100 * 1024 * 1024 ) ``` -------------------------------- ### Example Usage of Text Type Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/comments-and-relationships.md Example demonstrating how to extract plain text from a comment. ```swift let comments = try file.parseComments(forWorksheet: path) for comment in comments.commentList.items { if let text = comment.text.plain { print("Comment: \(text)") } } ``` -------------------------------- ### MergeCell Example Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/worksheet.md Example of printing the reference of merged cells. ```swift if let merges = worksheet.mergeCells { for merge in merges.items { print("Merged cells: \(merge.reference)") } } ``` -------------------------------- ### Row Example Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/worksheet.md Example of iterating through rows and cells in a worksheet. ```swift let worksheet = try file.parseWorksheet(at: path) for row in worksheet.data?.rows ?? [] { print("Row \(row.reference): \(row.cells.count) cells") for cell in row.cells { print(" \(cell.reference): \(cell.value ?? \"empty\")") } } ``` -------------------------------- ### CocoaPods Installation Source: https://github.com/coreoffice/corexlsx/blob/main/README.md Instructions for installing CoreXLSX using CocoaPods on Apple platforms. ```ruby source 'https://github.com/CocoaPods/Specs.git' # Uncomment the next line to define a global platform for your project # platform :ios, '9.0' use_frameworks! target '' do pod 'CoreXLSX', '~> 0.14.1' end ``` -------------------------------- ### Color Example Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/shared-strings.md Example of how to access and print color information from shared strings. ```swift let sharedStrings = try file.parseSharedStrings() if let sharedStrings = sharedStrings { for item in sharedStrings.items { for richText in item.richText { if let color = richText.properties?.color { if let rgb = color.rgb { print("Color #\(rgb)") } else if let theme = color.theme { print("Theme color: \(theme)") } } } } } ``` -------------------------------- ### Example Usage Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/styles.md Demonstrates how to parse styles and iterate through indexed RGB colors. ```swift let styles = try file.parseStyles() if let colors = styles.colors { for (index, color) in colors.indexed.rgbColors.enumerated() { if let rgb = color.rgb { print("Color \(index): #\(rgb)") } } } ``` -------------------------------- ### MergeCells Example Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/worksheet.md Example of accessing merged cell references. ```swift if let merges = worksheet.mergeCells { for merge in merges.items { print("Merged: \(merge.reference)") } } ``` -------------------------------- ### PageSetUpProperties Struct Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/worksheet.md Page setup configuration for printing. ```swift public struct PageSetUpProperties: Codable, Equatable { public let fitToPage: Bool? public let autoPageBreaks: Bool? } ``` -------------------------------- ### Font Example Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/styles.md Example of how to access and print font properties of a cell. ```swift let styles = try file.parseStyles() let worksheet = try file.parseWorksheet(at: path) if let cell = worksheet.data?.rows.first?.cells.first { if let font = cell.font(in: styles) { if let name = font.name { print("Font: \(name.value)") } if let size = font.size { print("Size: \(size.value)pt") } if let bold = font.bold?.value, bold { print("Bold: yes") } if let italic = font.italic?.value, italic { print("Italic: yes") } } } ``` -------------------------------- ### Worksheet Example Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/worksheet.md Example of accessing cell data, worksheet dimensions, and column formatting. ```swift let worksheet = try file.parseWorksheet(at: worksheetPath) // Access cell data if let data = worksheet.data { for row in data.rows { for cell in row.cells { print("Cell \(cell.reference): \(cell.value ?? \"empty\")") } } } // Get worksheet dimensions if let dim = worksheet.dimension { print("Worksheet covers: \(dim.reference)") } // Access column formatting if let columns = worksheet.columns { for col in columns.items { print("Column \(col.min)-\(col.max): width \(col.width)") } } ``` -------------------------------- ### Example Usage of parseComments Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/comments-and-relationships.md Example demonstrating how to parse comments from a worksheet and iterate through them. ```swift let file = try XLSXFile(filepath: "spreadsheet.xlsx")! let paths = try file.parseWorksheetPaths() for path in paths { do { let comments = try file.parseComments(forWorksheet: path) for (cellRef, comment) in comments.commentList.itemsByReference { print("Comment at \(cellRef): \(comment.text.plain ?? "")") } } catch CoreXLSXError.unsupportedWorksheetPath { print("Cannot parse comments: unsupported path \(path)") } catch { print("Parsing failed: \(error)") } } ``` -------------------------------- ### Example Usage of Comments Type Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/comments-and-relationships.md Example demonstrating how to access comment count and iterate through comments using the Comments type. ```swift let comments = try file.parseComments(forWorksheet: path) print("Total comments: \(comments.commentList.items.count)") for comment in comments.commentList.items { print("Cell \(comment.reference): \(comment.text.plain ?? "")") } ``` -------------------------------- ### Debug: inspect file structure Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/comments-and-relationships.md Example of how to inspect file structure by parsing relationships. ```swift // Debug: inspect file structure let relationships = try file.parseRelationships() for rel in relationships.items { print("\(rel.id): \(rel.type) -> \(rel.target)") } ``` -------------------------------- ### XLSXFile Data-Based Initialization Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/configuration.md Initializes an XLSXFile instance from in-memory Data. Examples show initialization from file data, network response, and app bundle. ```swift public init( data: Data, bufferSize: UInt32 = 10 * 1024 * 1024, errorContextLength: UInt = 0 ) throws ``` ```swift // From file data let fileURL = URL(fileURLWithPath: "./spreadsheet.xlsx") let data = try Data(contentsOf: fileURL) let file = try XLSXFile(data: data) // From network response let (data, _) = try await URLSession.shared.data(from: downloadURL) let file = try XLSXFile(data: data) // From app bundle let bundleURL = Bundle.main.url(forResource: "template", withExtension: "xlsx")! let bundleData = try Data(contentsOf: bundleURL) let file = try XLSXFile(data: bundleData) ``` -------------------------------- ### Worksheet.Dimension Example Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/worksheet.md Example of accessing the worksheet's used cell range. ```swift if let dimension = worksheet.dimension { print("Used cells: \(dimension.reference)") } ``` -------------------------------- ### cells(atColumns:) Example Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/worksheet.md Example of using the cells(atColumns:) method to retrieve cells from a specific column. ```swift let worksheet = try file.parseWorksheet(at: path) if let colC = ColumnReference("C") { let columnCCells = worksheet.cells(atColumns: [colC]) for cell in columnCCells { print("Cell \(cell.reference): \(cell.value ?? \"empty\")") } } ``` -------------------------------- ### Example Usage Source: https://github.com/coreoffice/corexlsx/blob/main/README.md This code snippet demonstrates how to open an XLSX file, parse its workbooks and worksheets, and print the raw cell data from each worksheet. ```swift import CoreXLSX let filepath = "./categories.xlsx" guard let file = XLSXFile(filepath: filepath) else { fatalError("XLSX file at \(filepath) is corrupted or does not exist") } for wbk in try file.parseWorkbooks() { for (name, path) in try file.parseWorksheetPathsAndNames(workbook: wbk) { if let worksheetName = name { print("This worksheet has a name: \(worksheetName)") } let worksheet = try file.parseWorksheet(at: path) for row in worksheet.data?.rows ?? [] { for c in row.cells { print(c) } } } } ``` -------------------------------- ### Example Usage of CommentList Type Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/comments-and-relationships.md Examples demonstrating different ways to access comments using the CommentList type, including array access, dictionary lookup, and iteration. ```swift let comments = try file.parseComments(forWorksheet: path) // Method 1: Direct array access for comment in comments.commentList.items { print("\(comment.reference): \(comment.text.plain ?? "")") } // Method 2: Dictionary lookup if let comment = comments.commentList.itemsByReference["A1"] { print("Comment at A1: \(comment.text.plain ?? "")") } // Method 3: Iterate dictionary for (ref, comment) in comments.commentList.itemsByReference { print("Comment at \(ref): \(comment.text.plain ?? "")") } ``` -------------------------------- ### Fetch all strings in a column Source: https://github.com/coreoffice/corexlsx/blob/main/CHANGELOG.md Example demonstrating how to fetch all string values (including shared strings) from a specified column using the new API. ```swift let sharedStrings = try file.parseSharedStrings() let columnCStrings = worksheet.cells(atColumns: [ColumnReference("C")!]) .compactMap { $0.stringValue(sharedStrings) } ``` -------------------------------- ### cells(atRows:) Example Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/worksheet.md Example of using the cells(atRows:) method to retrieve cells from specific rows. ```swift let worksheet = try file.parseWorksheet(at: path) let cells = worksheet.cells(atRows: [1, 2, 3]) for cell in cells { print("Cell \(cell.reference): \(cell.value ?? \"empty\")") } ``` -------------------------------- ### Parsing Styles and Fonts Source: https://github.com/coreoffice/corexlsx/blob/main/README.md Example of parsing style information, specifically fetching a list of font names used in the spreadsheet. ```swift let styles = try file.parseStyles() let fonts = styles.fonts?.items.compactMap { $0.name?.value } ``` -------------------------------- ### dateValue Example Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/cell.md Example of iterating through cells and printing date values. ```swift let worksheet = try file.parseWorksheet(at: path) for row in worksheet.data?.rows ?? [] { for cell in row.cells { if let date = cell.dateValue { let formatter = DateFormatter() formatter.dateStyle = .medium print("Date: \(formatter.string(from: date))") } } } ``` -------------------------------- ### Accessing Styles Information Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/styles.md Example demonstrating how to access and iterate through fonts, number formats, and colors within the Styles object. ```swift let styles = try file.parseStyles() // Access fonts if let fonts = styles.fonts { for (index, font) in fonts.items.enumerated() { print("Font \(index): \(font.name?.value ?? \"default\")") } } // Access number formats if let numFormats = styles.numberFormats { for fmt in numFormats.items { print("Format \(fmt.id): \(fmt.formatCode)") } } // Access colors if let colors = styles.colors { for color in colors.indexed.rgbColors { print("Color: \(color.rgb ?? \"indexed\")") } } ``` -------------------------------- ### Debug Malformed Files Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/errors.md Example of enabling error context for debugging malformed XLSX files. ```swift let file = try XLSXFile( data: fileData, errorContextLength: 20 // Show 20 chars before/after error ) ``` -------------------------------- ### Catching dataIsNotAnArchive Error Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/errors.md Example of how to catch the 'dataIsNotAnArchive' error when initializing an XLSXFile from Data. ```swift do { let file = try XLSXFile(data: fileData) } catch CoreXLSXError.dataIsNotAnArchive { print("The provided data is not a valid XLSX file") } catch { print("Other error: \(error)") } ``` -------------------------------- ### cells(atColumns:rows:) Example Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/worksheet.md Example of using the cells(atColumns:rows:) method to retrieve cells at the intersection of specified rows and columns. ```swift let worksheet = try file.parseWorksheet(at: path) if let colA = ColumnReference("A"), let colB = ColumnReference("B") { let cells = worksheet.cells(atColumns: [colA, colB], rows: [1, 2, 3]) for cell in cells { print("\(cell.reference): \(cell.value ?? \"\")") } } ``` -------------------------------- ### Swift Package Manager Installation Source: https://github.com/coreoffice/corexlsx/blob/main/README.md Instructions for adding CoreXLSX as a dependency using Swift Package Manager in a Swift package. ```swift dependencies: [ .package(url: "https://github.com/CoreOffice/CoreXLSX.git", .upToNextMinor(from: "0.14.1")) ] ``` -------------------------------- ### stringValue(_:) Example Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/cell.md Example of using stringValue to extract strings from cells in a column. ```swift let sharedStrings = try file.parseSharedStrings() let worksheet = try file.parseWorksheet(at: path) if let sharedStrings = sharedStrings { if let colC = ColumnReference("C") { let columnCStrings = worksheet.cells(atColumns: [colC]) .compactMap { $0.stringValue(sharedStrings) } for str in columnCStrings { print("String: \(str)") } } } ``` -------------------------------- ### Catching archiveEntryNotFound Error Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/errors.md Example of how to catch the 'archiveEntryNotFound' error when parsing a worksheet. ```swift do { let worksheet = try file.parseWorksheet(at: "xl/worksheets/sheet1.xml") } catch CoreXLSXError.archiveEntryNotFound { print("Worksheet not found at specified path") } catch { print("Other error: \(error)") } ``` -------------------------------- ### richStringValue(_:) Example Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/cell.md Example of iterating through cells and extracting rich text values. ```swift let sharedStrings = try file.parseSharedStrings() let worksheet = try file.parseWorksheet(at: path) if let sharedStrings = sharedStrings { for row in worksheet.data?.rows ?? [] { for cell in row.cells { let richTexts = cell.richStringValue(sharedStrings) for richText in richTexts { print("Text: \(richText.text ?? "")") if let props = richText.properties { if let font = props.font { print(" Font: \(font.value)") } } } } } } ``` -------------------------------- ### Catching unsupportedWorksheetPath Error Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/errors.md Example of how to catch the 'unsupportedWorksheetPath' error when parsing comments. ```swift do { let comments = try file.parseComments(forWorksheet: "custom/path/sheet.xml") } catch CoreXLSXError.unsupportedWorksheetPath { print("Cannot parse comments: worksheet path format not recognized") } catch { print("Other error: \(error)") } ``` -------------------------------- ### Worksheet.Properties Structure Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/worksheet.md Sheet-level properties including page setup configuration. ```swift public struct Properties: Codable, Equatable { public let pageSetUpProperties: PageSetUpProperties? } ``` -------------------------------- ### Accessing Cell Format Properties Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/styles.md Example showing how to retrieve and print properties of a cell's format, including alignment details. ```swift let styles = try file.parseStyles() let worksheet = try file.parseWorksheet(at: path) if let firstCell = worksheet.data?.rows.first?.cells.first { if let format = firstCell.format(in: styles) { print("Number format ID: \(format.numberFormatId)") if let align = format.alignment { print("Horizontal: \(align.horizontal ?? \"default\")") print("Vertical: \(align.vertical ?? \"default\")") print("Wrap text: \(align.wrapText ?? false)") } } } ``` -------------------------------- ### Example Usage of SharedStrings Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/shared-strings.md Demonstrates how to parse shared strings and retrieve string values from a specific column in a worksheet. ```swift let sharedStrings = try file.parseSharedStrings() let worksheet = try file.parseWorksheet(at: path) if let sharedStrings = sharedStrings { // Get strings from column C if let colC = ColumnReference("C") { let columnCCells = worksheet.cells(atColumns: [colC]) let columnCStrings = columnCCells.compactMap { $0.stringValue(sharedStrings) } for str in columnCStrings { print("String: \(str)") } } } ``` -------------------------------- ### Validate Input Before Processing Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/errors.md Example of validating worksheet paths before attempting to parse a specific worksheet. ```swift // Validate worksheet path before using it let paths = try file.parseWorksheetPaths() guard paths.contains(worksheetPath) else { print("Worksheet path not found") return } let worksheet = try file.parseWorksheet(at: worksheetPath) ``` -------------------------------- ### ColumnReference Example Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/cell.md Demonstrates creating ColumnReference from letters and numbers, and using it in cell queries. ```swift // Create from letters if let colA = ColumnReference("A") { print("Column A (int: \(colA.intValue))") } if let colAA = ColumnReference("AA") { print("Column AA (int: \(colAA.intValue))") } // Create from number if let col27 = ColumnReference(27) { print("Column 27: \(col27.value)") // prints "AA" } // Use in cell queries let worksheet = try file.parseWorksheet(at: path) if let columnB = ColumnReference("B") { let bCells = worksheet.cells(atColumns: [columnB]) for cell in bCells { print("\(cell.reference)") } } ``` -------------------------------- ### Getting Cell Formatting and Font Source: https://github.com/coreoffice/corexlsx/blob/main/README.md Demonstrates how to retrieve the format and font information for a specific cell using parsed styles. ```swift let styles = try file.parseStyles() let format = worksheet.data?.rows.first?.cells.first?.format(in: styles) let font = worksheet.data?.rows.first?.cells.first?.font(in: styles) ``` -------------------------------- ### Handling XML Decoding Errors Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/errors.md Example of how to catch and handle specific XML decoding errors from the underlying XMLCoder library, as well as CoreXLSX errors. ```swift do { let styles = try file.parseStyles() } catch let error as NSError where error.domain == "XMLCoderError" { print("XML decoding error: \(error.userInfo)") } catch CoreXLSXError.archiveEntryNotFound { print("Styles file not found") } catch { print("Unexpected error: \(error)") } ``` -------------------------------- ### Get cells from specific columns Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/INDEX.md This example demonstrates how to retrieve cells that belong to specific columns within a worksheet using ColumnReference. ```swift let worksheet = try file.parseWorksheet(at: path) if let colA = ColumnReference("A"), let colB = ColumnReference("B") { let cells = worksheet.cells(atColumns: [colA, colB]) for cell in cells { print("\(cell.reference): \(cell.value ?? "")") } } ``` -------------------------------- ### Example Usage of SharedStrings.Item Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/shared-strings.md Iterates through shared string items and prints whether they are plain text or rich text. ```swift let sharedStrings = try file.parseSharedStrings() if let sharedStrings = sharedStrings { for item in sharedStrings.items { if let plainText = item.text { print("Plain: \(plainText)") } else if !item.richText.isEmpty { print("Rich text with \(item.richText.count) segments") } } } ``` -------------------------------- ### Accessing Formula Details Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/cell.md Example showing how to access the formula value and calculation index from a cell. ```swift let cell = worksheet.data?.rows.first?.cells.first if let formula = cell?.formula { print("Formula: \(formula.value ?? \"\")") if let calcIdx = formula.calculationIndex { print("Calculation index: \(calcIdx)") } } ``` -------------------------------- ### Simple Case: Local File Initialization Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/configuration.md Basic initialization of XLSXFile with a local file path. ```swift guard let file = XLSXFile(filepath: "./data.xlsx") else { print("Cannot open file") return } let workbooks = try file.parseWorkbooks() ``` -------------------------------- ### Handling Different Cell Types Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/cell.md Example demonstrating how to process cells based on their CellType, including retrieving shared string values, numeric values, and date values. ```swift for row in worksheet.data?.rows ?? [] { for cell in row.cells { switch cell.type { case .sharedString: if let sharedStrings = try file.parseSharedStrings() { if let str = cell.stringValue(sharedStrings) { print("String: \(str)") } } case .number: if let num = Double(cell.value ?? "") { print("Number: \(num)") } case .date: if let date = cell.dateValue { print("Date: \(date)") } default: print("Other: \(cell.value ?? \"\")") } } } ``` -------------------------------- ### XLSXFile File-Based Initialization Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/configuration.md Initializes an XLSXFile instance by reading from a filesystem path. Demonstrates basic initialization, initialization with a larger buffer size, and initialization with error context length. ```swift public init?( filepath: String, bufferSize: UInt32 = 10 * 1024 * 1024, errorContextLength: UInt = 0 ) ``` ```swift import CoreXLSX let filepath = "./data/spreadsheet.xlsx" // Basic initialization guard let file = XLSXFile(filepath: filepath) else { fatalError("Cannot open \(filepath)") } // With larger buffer for big files guard let file = XLSXFile( filepath: filepath, bufferSize: 50 * 1024 * 1024 // 50MB ) else { fatalError("Cannot open \(filepath)") } // With error context for debugging malformed files guard let file = XLSXFile( filepath: filepath, errorContextLength: 20 // Show 20 chars before/after error ) else { fatalError("Cannot open \(filepath)") } ``` -------------------------------- ### Iterating Through Cells in a Worksheet Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/cell.md Example of how to iterate through all cells in a worksheet, printing their reference, type, and value. It also shows how to access formula details if present. ```swift let worksheet = try file.parseWorksheet(at: path) for row in worksheet.data?.rows ?? [] { for cell in row.cells { print("Cell \(cell.reference)") print(" Type: \(cell.type?.rawValue ?? \"none\")") print(" Value: \(cell.value ?? \"empty\")") if let formula = cell.formula { print(" Formula: \(formula.value ?? \"\")") } } } ``` -------------------------------- ### Network Downloaded File Initialization Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/configuration.md Initialization of XLSXFile from data downloaded from a network URL. ```swift let (data, response) = try await URLSession.shared.data(from: url) let file = try XLSXFile(data: data) let workbooks = try file.parseWorkbooks() ``` -------------------------------- ### App Bundle Resource Initialization Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/configuration.md Initialization of XLSXFile from data loaded from an app bundle resource. ```swift let url = Bundle.main.url(forResource: "template", withExtension: "xlsx")! let data = try Data(contentsOf: url) let file = try XLSXFile(data: data) let workbooks = try file.parseWorkbooks() ``` -------------------------------- ### Path Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/types.md File path representation with components. ```swift public struct Path { public let value: String public let isRoot: Bool public let components: [Substring] } ``` -------------------------------- ### Debugging Corrupted File Initialization Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/configuration.md Initialization of XLSXFile with data and an increased error context length for debugging corrupted files. ```swift let file = try XLSXFile( data: data, errorContextLength: 20 ) do { let workbooks = try file.parseWorkbooks() } catch { print("Parsing failed: \(error)") // Error includes context } ``` -------------------------------- ### Large File Initialization Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/configuration.md Initialization of XLSXFile for large files with a specified buffer size. ```swift let file = XLSXFile( filepath: largeFilePath, bufferSize: 50 * 1024 * 1024 ) let workbooks = try file.parseWorkbooks() ``` -------------------------------- ### Handle Large Files Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/errors.md Shows how to use the `bufferSize` parameter when initializing `XLSXFile` for files larger than 10MB. ```swift let file = XLSXFile( filepath: filepath, bufferSize: 50 * 1024 * 1024 // 50MB buffer ) ``` -------------------------------- ### XLSXFile Class Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/types.md Entry point for reading XLSX files. ```swift public class XLSXFile { public init( filepath: String, bufferSize: UInt32 = 10 * 1024 * 1024, errorContextLength: UInt = 0 ) #if swift(>=5.0) public init( data: Data, bufferSize: UInt32 = 10 * 1024 * 1024, errorContextLength: UInt = 0 ) throws #endif } ``` -------------------------------- ### XLSXFile Initializer (filepath) Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/xlsxfile.md Creates an instance by reading a file from the filesystem path. ```swift public init?( filepath: String, bufferSize: UInt32 = 10 * 1024 * 1024, errorContextLength: UInt = 0 ) ``` ```swift import CoreXLSX let filepath = "./categories.xlsx" guard let file = XLSXFile(filepath: filepath) else { fatalError("XLSX file at \(filepath) is corrupted or does not exist") } // Parse and read content for wbk in try file.parseWorkbooks() { for (name, path) in try file.parseWorksheetPathsAndNames(workbook: wbk) { let worksheet = try file.parseWorksheet(at: path) for row in worksheet.data?.rows ?? [] { for cell in row.cells { print(cell) } } } } ``` -------------------------------- ### Workbook Struct Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/types.md Top-level workbook structure. ```swift public struct Workbook: Codable, Equatable { public let views: Views? public let sheets: Sheets } ``` -------------------------------- ### Catching invalidCellReference Error Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/errors.md Example of how to catch the 'invalidCellReference' error during cell reference decoding. ```swift let cellRefString = "InvalidCell" do { let cellRef = try decoder.decode(CellReference.self, from: cellRefString.data(using: .utf8)!) } catch CoreXLSXError.invalidCellReference { print("Cell reference is malformed") } catch { print("Other error: \(error)") } ``` -------------------------------- ### Create Column References Safely Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/errors.md Demonstrates safe creation of `ColumnReference` objects, as their initializers return optionals. ```swift // ColumnReference initializers return optionals guard let colA = ColumnReference("A") else { print("Invalid column reference") return } let cells = worksheet.cells(atColumns: [colA]) ``` -------------------------------- ### XLSXFile Initializer (data) Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/xlsxfile.md Creates an instance by reading from data in memory (Swift 5.0 or later only). ```swift public init( data: Data, bufferSize: UInt32 = 10 * 1024 * 1024, errorContextLength: UInt = 0 ) throws ``` ```swift let fileData = try Data(contentsOf: fileURL) let file = try XLSXFile(data: fileData) for wbk in try file.parseWorkbooks() { // Process workbooks } ``` -------------------------------- ### TableStyle Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/types.md Single table style. ```swift public struct TableStyle: Codable, Equatable { public let pivot: Bool public let name: String public let count: Int public let elements: [Element] public struct Element: Codable, Equatable { public let type: String } } ``` -------------------------------- ### Accessing Cell Reference Properties Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/cell.md Example of iterating through cells and printing their reference, column, and row details. ```swift let worksheet = try file.parseWorksheet(at: path) for row in worksheet.data?.rows ?? [] { for cell in row.cells { let ref = cell.reference print("Cell at \(ref.description)") print(" Column: \(ref.column.description)") print(" Row: \(ref.row)") } } ``` -------------------------------- ### Workbook.Views Structure Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/workbook.md Container for workbook view configurations. ```swift public struct Views: Codable, Equatable { public let items: [View] } ``` -------------------------------- ### Including Error Context Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/errors.md Demonstrates how to use the `errorContextLength` parameter to include context snippets in XML decoding errors for better debugging. ```swift let file = try XLSXFile( data: fileData, errorContextLength: 15 // Include 15 chars of context around error ) ``` -------------------------------- ### Handling Missing Optional Content Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/errors.md Illustrates the correct way to handle potentially missing optional content, such as shared strings, using optional binding instead of catching errors. ```swift // Correct: SharedStrings may not exist if let sharedStrings = try file.parseSharedStrings() { // Process shared strings } // Incorrect: Don't catch archiveEntryNotFound for optional content let sharedStrings = try? file.parseSharedStrings() ``` -------------------------------- ### Example Usage of RichText Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/shared-strings.md Iterates through cells in a worksheet, extracts rich string values, and prints their text and formatting properties. ```swift let sharedStrings = try file.parseSharedStrings() let worksheet = try file.parseWorksheet(at: path) if let sharedStrings = sharedStrings { for row in worksheet.data?.rows ?? [] { for cell in row.cells { let richTexts = cell.richStringValue(sharedStrings) for richText in richTexts { print("Text: \(richText.text ?? "")") if let props = richText.properties { if let font = props.font { print(" Font: \(font.value)") } if let size = props.size { print(" Size: \(size.value)") } if let color = props.color { if let rgb = color.rgb { print(" RGB: \(rgb)") } else if let theme = color.theme { print(" Theme: \(theme)") } } } } } } } ``` -------------------------------- ### Workbook.View Structure Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/workbook.md Represents a workbook view configuration, including window position and size. ```swift public struct View: Codable, Equatable { public let xWindow: Int? public let yWindow: Int? public let windowWidth: UInt? public let windowHeight: UInt? } ``` -------------------------------- ### Workbook.View Properties Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/workbook.md Properties of the View struct. ```swift public let xWindow: Int? public let yWindow: Int? public let windowWidth: UInt? public let windowHeight: UInt? ``` -------------------------------- ### Relationships Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/types.md Container for relationship entries. ```swift public struct Relationships: Codable, Equatable { public let items: [Relationship] } ``` -------------------------------- ### Workbook.Sheet Properties Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/workbook.md Properties of the Sheet struct. ```swift public let name: String? public let id: String public let relationship: String ``` -------------------------------- ### Get dates, numbers, and parse cell formatting Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/INDEX.md This code snippet illustrates how to extract date and numeric values from cells, and how to access cell formatting information such as number format and font details. ```swift let styles = try file.parseStyles() let worksheet = try file.parseWorksheet(at: path) for row in worksheet.data?.rows ?? [] { for cell in row.cells { // Extract date if let date = cell.dateValue { print("Date: \(date)") } // Extract number if let num = Double(cell.value ?? "") { print("Number: \(num)") } // Get formatting if let format = cell.format(in: styles) { print("Format ID: \(format.numberFormatId)") } // Get font if let font = cell.font(in: styles) { print("Font: \(font.name?.value ?? \"default\")") } } } ``` -------------------------------- ### Workbook.Views Properties Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/workbook.md Properties of the Views struct. ```swift public let items: [View] ``` -------------------------------- ### Workbook.Sheets Properties Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/workbook.md Properties of the Sheets struct. ```swift public let items: [Sheet] ``` -------------------------------- ### Workbook.Sheets Structure Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/workbook.md Container for sheet definitions. ```swift public struct Sheets: Codable, Equatable { public let items: [Sheet] } ``` -------------------------------- ### Format Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/types.md Cell format specification. ```swift public struct Format: Codable, Equatable { public let numberFormatId: Int public let fontId: Int public let borderId: Int? public let fillId: Int? public let applyNumberFormat: Bool? public let applyFont: Bool? public let applyFill: Bool? public let applyBorder: Bool? public let applyAlignment: Bool? public let applyProtection: Bool? public let alignment: Alignment? public struct Alignment: Codable, Equatable { public let vertical: String? public let horizontal: String? public let wrapText: Bool? } } ``` -------------------------------- ### Colors Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/types.md Indexed color palette. ```swift public struct Colors: Codable, Equatable { public let indexed: Indexed public struct Indexed: Codable, Equatable { public let rgbColors: [Color] } } ``` -------------------------------- ### Font Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/types.md Font properties. ```swift public struct Font: Codable, Equatable { public let size: Size? public let color: Color? public let name: Name? public let bold: Bold? public let italic: Italic? public let strike: Strike? public struct Size: Codable, Equatable { public let value: Double } public struct Name: Codable, Equatable { public let value: String } public struct Bold: Codable, Equatable { public let value: Bool? } public struct Italic: Codable, Equatable { public let value: Bool? } public struct Strike: Codable, Equatable { public let value: Bool? } } ``` -------------------------------- ### Relationship Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/types.md Single relationship entry. ```swift public struct Relationship: Codable, Equatable { public let id: String public let type: SchemaType public let target: String } ``` -------------------------------- ### Parsing Date Values Source: https://github.com/coreoffice/corexlsx/blob/main/README.md Shows how to extract date values from cells using the `dateValue` property. ```swift let columnCDates = worksheet.cells(atColumns: [ColumnReference("C")!]) .compactMap { $0.dateValue } ``` -------------------------------- ### Handling Invalid Cell References with Optional Return Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/errors.md Demonstrates how ColumnReference initializers return nil for invalid input instead of throwing. ```swift // These return nil for invalid input rather than throwing if let colA = ColumnReference("A") { // Valid column reference } if let colRef = ColumnReference("99") { // Valid: converts numeric column index to letters } ``` -------------------------------- ### parseDocumentPaths() Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/comments-and-relationships.md Returns paths to all documents referenced by root relationships. Typically contains one path to the main workbook. ```swift public func parseDocumentPaths() throws -> [String] ``` ```swift let docPaths = try file.parseDocumentPaths() for path in docPaths { print("Document: \(path)") } ``` -------------------------------- ### Worksheet Struct Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/types.md Single worksheet within a workbook. ```swift public struct Worksheet: Codable { public let properties: Properties? public let dimension: Dimension? public let sheetViews: SheetViews? public let formatProperties: FormatProperties? public let columns: Columns? public let data: Data? public let mergeCells: MergeCells? } ``` -------------------------------- ### Workbook Properties Source: https://github.com/coreoffice/corexlsx/blob/main/_autodocs/api-reference/workbook.md Properties of the Workbook struct, detailing its components. ```swift public let views: Views? public let sheets: Sheets ```