在Mac OS X 10.6 Snow
Leopard中,Apple引入了ApplescriptObjC框架,该框架使可可和Applescript之间的交互变得非常容易。可以在同一源文件中使用Applescript代码和类似Objective-
C的语法。它比
scripting Bridge和更方便
NSApplescript。
ApplescriptObjC无法直接在Swift中使用,因为
loadApplescriptObjectiveCscriptsNSBundle
的命令未桥接到Swift。
但是,您可以使用例如Objective-C桥类
ASObjC.h
@import Foundation;@import ApplescriptObjC;@interface NSObject (Excel)- (void)openExceldocument:(NSString *)filePath;- (NSArray *)valueOfUsedRange;@end@interface ASObjC : NSObject+ (ASObjC *)sharedASObjC;@property id Excel;@end
ASObjC.m
#import "ASObjC.h"@implementation ASObjC+ (void)initialize{ if (self == [ASObjC class]) { [[NSBundle mainBundle] loadApplescriptObjectiveCscripts]; }}+ (ASObjC *)sharedASObjC{ static id sharedInstance = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedInstance = [[ASObjC alloc] init]; }); return sharedInstance;}- (instancetype)init{ self = [super init]; if (self) { _Excel = NSClassFromString(@"ASExcel"); } return self;}@end从ApplescriptObjC模板创建Applescript源文件
ASExcel.apple脚本
script ASExcel property parent: class "NSObject" on openExceldocument:filePath set asFilePath to filePath as text tell application "Microsoft Excel" set sourceBook to open workbook workbook file name asFilePath repeat try get workbooks return end try delay 0.5 end repeat end tell end opendocument on valueOfUsedRange() tell application "Microsoft Excel" tell active sheet set activeRange to used range return value of activeRange end tell end tell end valueOfUsedRangeend script
如有必要,链接到ApplescriptObjC框架。
创建桥接头并导入
ASObjC.h
然后您可以使用以下命令从Swift调用ApplescriptObjC
ASObjC.sharedASObjC().Excel.openExceldocument("Macintosh HD:Users:MyUser:Path:To:ExcelFile.xlsx")要么
let excelData = ASObjC.sharedASObjC().Excel.valueOfUsedRange() as! Array<[String]>



