5

I like to open a .xls file with Excel on macOS. I only found examples for C# but not for Swift.

Bonus question: Is it possible to launch that file with Excel also, even if this file extension is not associated with Excel?

joe
  • 2,468
  • 2
  • 12
  • 19
PjotrC
  • 311
  • 1
  • 6
  • 16
  • You can open a file with the associated program by using the terminal command `open /path/to/file`. You can do this in swift by using `NSTask` – Palle Jun 21 '16 at 23:16

1 Answers1

12

There is NSWorkspace.sharedWorkspace().openURL(fileURL) or NSWorkspace.sharedWorkspace().openFile(fileURL.path!) in order to open files by their default application.

If you want to force Excel, you can use NSWorkspace.sharedWorkspace().openFile(fileURL.path!, withApplication: "Microsoft Excel").

If you prefer forcing Excel and using URL objects, then there's the excessive openURLs(_:withAppBundleIdentifier:options:additionalEventParamDescriptor:launchIdentifiers)

Though it is not a big deal yet I am updating the syntax as per Swift 4.2 -

NSWorkspace.shared.openFile(fileURL!.path)
NSWorkspace.shared.openFile(fileURL!.path, withApplication: "Microsoft Excel")
NSWorkspace.shared.open([fileURL!], withAppBundleIdentifier: "com.microsoft.Excel", options: NSWorkspace.LaunchOptions.withErrorPresentation, additionalEventParamDescriptor: nil, launchIdentifiers: nil)

To get the Bundle Identifier of any app, use this command in your terminal

 osascript -e 'id of app "*app_name*"'
Ashutosh Shukla
  • 358
  • 5
  • 14
Kevin Low
  • 2,672
  • 16
  • 17