4

For my app, I want to be able to import an excel sheet into Xcode and then use swift to programatically extract relevant pieces of data. I want to be able to access the data like a 2d-array.

I basically want a 2d array but just one then I can pre-import from an excel file.

I want to be able to call the piece of data in a particular cell, so for example I can get the data in cell A5.

I'm using Xcode 9.2, swift 4.

Callum Williams
  • 121
  • 2
  • 9
  • Provide more information about how you wish to access excel sheet data from swift? – Serhii Didanov Jan 11 '18 at 14:40
  • You may want to look at this. [Swift Excel Xlsx Reader Writer](https://github.com/joelparkerhenderson/demo_swift_excel_xlsx_reader_writer) also you will always get more help if you show the code that you have an issue with rather than expecting some to give you the code. You also may want to consider importing the data via a csv and working it that way. – MwcsMac Jan 11 '18 at 15:44

1 Answers1

2

There is an open-source library CoreXLSX that can be imported into your project either with CocoaPods or Swift Package Manager. After it's integrated with your project you can import its module and use it this way:

import CoreXLSX

guard let file = XLSXFile(filepath: "./categories.xlsx") else {
  fatalError("XLSX file corrupted or does not exist")
}

for path in try file.parseWorksheetPaths() {
  let ws = try file.parseWorksheet(at: path)
  for row in ws.data?.rows ?? [] {
    for c in row.cells {
      print(c)
    }
  }
}
Max Desiatov
  • 5,087
  • 3
  • 48
  • 56
  • I am not able to get string value from .xlsx file by .parsewoeksheetPaths. It only returning integer value, How can I get string value? – Diva Feb 16 '19 at 16:12
  • 1
    Since CoreXLSX 0.4 there is a new API for this: `parseSharedString()`. Some cells (usually with strings) have their values shared in a separate model type, which you can get by evaluating `try file.parseSharedString()`. You can refer to [the SharedStrings model](https://github.com/MaxDesiatov/CoreXLSX/blob/master/Sources/CoreXLSX/SharedStrings.swift) for the full list of its properties. – Max Desiatov Feb 17 '19 at 13:07
  • but using parseSharedString() , I am getting unique value string of .xlsx, in random order, not row wise. I want cell value row or column wise and if cell is empty then It should return empty string. – Diva Feb 17 '19 at 17:52
  • 1
    Sorry about the confusion @Diva, the documentation should really state that the strings returned by `parseSharedString()` don't have a random order. Those can be addressed by index that you get from cells returned by `parseWorksheetPaths()`. That's now clarified with [example code in the README file](https://github.com/MaxDesiatov/CoreXLSX#shared-strings). – Max Desiatov Feb 21 '19 at 11:26
  • @MaxDesiatov. Can i write to excel files using this library? – Awais Fayyaz Dec 21 '19 at 07:52