Modeling Tabular Data from Excel file in Swift

Hi,


I'm working on a project where I have tabular data provided in an excel file (.xlsx). I am trying to figure out how to bring in or model that data in Swift so I can query a specific row and column combination. I had a couple of thoughts on this:


1. Use a third party library like CoreXLSX to read the data directly from the excel file

2. I found Apple's MLDataTable API pretty interesting. Can this be used for non machine learning tasks? From the documentation, it looks like its use-case is for machine learning rather than being a general purpose data table class?


Thanks!

Replies

1. Use a third party library like CoreXLSX to read the data directly from the excel file


If you have it already done, that's the easiest way to go.

Check a few points :

- price of licence (as well as runtime price)

- Does it covers your localization needs when reading data (decimal separators…)


2. Apple's MLDataTable API

I never used MLDataTable API. Is the output format suited to your app needs ?


Otherwise, it is not that difficult to write the routines to read the Excel file in CSV format.

Thanks! Those are some fantastic points, let me do some research into those!

Good luck.


Once you have concluded, don't forget to close the thread.

hi,


if you're willing to turn the Excel file into tab-separated text, it is easy to read the data into whatever is your data model. assuming your spreadsheet has column titles along its top row, the code below will give you a dictionary for every data row in the spreadsheet, keyed by the column titles


var theDatabase = YourDatabase()  // whatever is your database model

// read the file as one big string
var fileContents:String
do {
  fileContents = try String(contentsOfFile: destinationPath, encoding: String.Encoding.utf8)
} catch let error {
  print("Error reading file: \(error.localizedDescription)")
  fileContents = ""
}

guard fileContents.count>0 else {
  return theDatabase
}

// split out records (separated by returns)
let records = fileContents.split { $0 == "\r" }

// first record is field names, i.e., column titles
let fieldNames = findFields(String(records[0]))

// all remaining records are data, so match each with field names of record 0
for k in 1..<records.count {
  let values = findFields(String(records[k]))
  var dictionary = [String:String]()
  for n in 0..<values.count {
  dictionary[fieldNames[n]] = values[n]
  }
  theDatabase.append(dictionary) // append would be a method in YourDatabase
}


if theDatabase above is simply an array of dictionaries, then you can get the data in a column labeled YOURLABEL and in row n just by referencing theDatabase[n]["YOURLABEL"].


hope that helps,

DMG

  • Hi, can you tell me what your findFields function looks like? That would be great. Thank you very much!

Add a Comment