in Cocoa, Core Data, Objective-C, Programming, Unix

Quick Spreadsheet to plist Technique

Imagine you have a huge list of names in a spreadsheet and you’d like to get this data into an Apple plist file to use in your iPhone/Mac app or import into a Core Data model. Such a long list of data would take forever to cut and paste so here is a really quick way to build that plist.

First, export your spreadsheet as a .csv file. Use Unicode UTF8 encoding if possible. Lets say I saved this file as StudentNames.csv in my Documents folder.

Next, create a new .php file and paste in the following code. I called mine student-exporter.php and placed it in my Documents folder also.

<!--?php
echo "(\n";
if (($handle = fopen("StudentNames.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        echo "\t\"" . $data[0] . "\",\n";
    }
    fclose($handle);
}
echo ")\n";

Now open the Terminal app on your Mac and type the following into the console:

cd ~/Documents
php -f student-exporter.php > Students.plist

This should create a Students.plist file that will open in Xcode. However this is using the old NextSTEP text plist format which was deprecated when Mac OS X 10.0 came out. To convert into the more compact binary format, type the following into the console:

plutil -convert binary1 Students.plist

Write a Comment

Comment

    • Your file system might be case-dependant. Perhaps try making sure the file’s name is lower-case as well as the string in the PHP file.

  1. This works for me, to the extent that it creates a list of strings, but it does not seem to assign more than the first field. I get an array of all the strings in the first column. Can this be used to get all the columns into dictionaries, each row being a single dictionary?

    • The NextStep plist format specifies a dictionary in the format as

      {
      “key” = “value”;
      “key” = “value”;
      }

      So you might want to change the middle line to iterate over each column as follows

      echo “\t\””;
      echo “{\n”;
      foreach($data as $key => $value) {
      echo “\t\”” . $key . “\” = “\” . $value . “\”;\n”
      }
      echo “}\n”;
      echo “\”,\n”;