SwiftCSVExport
Swift CSV Export 是一个 轻量级且功能丰富的框架,它 以简单的方式帮助创建、读取和写入 CSV 文件。它支持 Objective-C 和 Swift 项目。
特性
- 支持 Swift 4、4.2 和 5 以及最新版 Xcode (12)
- 可以使用属性键来指定 CSV 文件名、表头和行。
- 可以将 JSON 字符串转换为 CSV。
- 可以读取 CSV 文件并将其转换为 NSDictionary。
- 在写入 CSV 文件时可以启用/禁用严格验证。
- 可以读取 CSV 文件并将其转换为 CSV 类(面向对象方法)。
- 支持 CocoaPods、mac OS 和 Vapor 框架(Swift 包管理器)。
- 可以根据 String.Encoding 类型的编码方式对 CSV 进行编码(例如 utf8、ascii、unicode、utf16 等)。请参考:String.Encoding。
- 可以通过在项目中启用配置来在 iOS 文件应用中查看导出的 CSV 文档。
- 处理了 CSV 文件中的标点符号(\n、\t、等)字符。
Swift 版本
支持 Swift 4、4.2 和 5 以及最新版 Xcode
pod 'SwiftCSVExport' , '= 2.0.2' // Swift 4
pod 'SwiftCSVExport' , '= 2.0.3' // Swift 4.2
pod 'SwiftCSVExport' , '= 2.3.0' // Swift 5
pod 'SwiftCSVExport' , '= 2.6.0' // Latest Xcode 12
iOS/MacOS导入头文件
首先,需要导入框架。有关如何将框架添加到您的项目的安装说明。
//iOS - Objective-C
@import SwiftCSVExport;
//iOS - Swift
import SwiftCSVExport
//macOS - Old swift version < 4
import SwiftCSVExportOSX
//macOS - New swift version > 4
import SwiftCSVExport
配置
- 在您的项目.plist文件中添加以下键,以在iOS文件应用中查看导出的CSV文档。
Bundle display name - "APPLICATION NAME"
Application requires iPhone environment - YES
Supports opening documents in place - YES
Application supports iTunes file sharing - YES
示例
示例 1 - Objective-C
// First User Object
NSMutableDictionary *user1 = [NSMutableDictionary new];
[user1 setValue:@"vignesh" forKey:@"name" ];
[user1 setValue:@"[email protected]" forKey: @"email"];
// Secound User Object
NSMutableDictionary *user2 = [NSMutableDictionary new];
[user2 setValue:@"vinoth" forKey:@"name" ];
[user2 setValue:@"[email protected]" forKey: @"email"];
// CSV fields Array
NSMutableArray *fields = [NSMutableArray new];
[fields addObject:@"name"];
[fields addObject:@"email"];
// CSV rows Array
NSMutableArray *data = [NSMutableArray new];
[data addObject:user1];
[data addObject:user2];
NSString *userpath = [[CSVExport export] exportCSV:@"userlist1" fields:fields values:data];
NSLog(@"%@",userpath);
NSString *namepath = [[CSVExport export] exportCSV:@"userlist1" fields:@[@"name", @"email"] values:data];
NSLog(@"%@",namepath);
// Able to convert JSON string into CSV.
NSString *string = @"[{\"name\":\"vignesh\",\"email\":\"[email protected]\"},{\"name\":\"vinoth\",\"email\":\"[email protected]\"}]";
NSString *filePath = [[CSVExport export] exportCSVString:@"userlist1"fields:fields values:string];
NSLog(@"%@",filePath);
示例 2 - Swift - 面向对象方法
// First User Object
let user1:NSMutableDictionary = NSMutableDictionary()
user1.setObject(107, forKey: "userid" as NSCopying);
user1.setObject("vignesh", forKey: "name" as NSCopying);
user1.setObject("[email protected]", forKey: "email" as NSCopying);
user1.setObject(true, forKey:"isValidUser" as NSCopying)
user1.setObject("Hi 'Vignesh!' \nhow are you? \t Shall we meet tomorrow? \r Thanks ", forKey: "message" as NSCopying);
user1.setObject(571.05, forKey: "balance" as NSCopying);
// Secound User Object
let user2:NSMutableDictionary = NSMutableDictionary()
user2.setObject(108, forKey: "userid" as NSCopying);
user2.setObject("vinoth", forKey: "name" as NSCopying);
user2.setObject(false, forKey:"isValidUser" as NSCopying)
user2.setObject("[email protected]", forKey: "email" as NSCopying);
user2.setObject("Hi 'Vinoth!', \nHow are you? \t Shall we meet tomorrow? \r Thanks ", forKey: "message" as NSCopying);
user2.setObject(567.50, forKey: "balance" as NSCopying);
// Add fields into columns of CSV headers
let header = ["userid", "name", "email", "message", "isValidUser","balance"]
// Add dictionary into rows of CSV Array
let data:NSMutableArray = NSMutableArray()
data.add(user1);
data.add(user2);
// Create a object for write CSV
let writeCSVObj = CSV()
writeCSVObj.rows = data
writeCSVObj.delimiter = DividerType.comma.rawValue
writeCSVObj.fields = header as NSArray
writeCSVObj.name = "userlist"
// Write File using CSV class object
let result = exportCSV(writeCSVObj);
if result.isSuccess {
guard let filePath = result.value else {
print("Export Error: \(String(describing: result.value))")
return
}
self.testWithFilePath(filePath, rowCount: data.count, columnCount: header.count)
print("File Path: \(filePath)")
// Read File and convert as CSV class object
let readCSVObj = readCSVObject(filePath);
// Use 'SwiftLoggly' pod framework to print the Dictionary
loggly(LogType.Info, text: readCSVObj.name)
} else {
print("Export Error: \(String(describing: result.value))")
}
写入与读取输出
File Path: xxxxxx/xxxxxxx/Documents/Exports/userlist.csv
userid,name,email,message,isValidUser,balance
107, "vignesh", "[email protected]", "Hi 'Vignesh!' \nhow are you? \t Shall we meet tomorrow? \r Thanks ", 1, 571.05
108, "vinoth", "[email protected]", "Hi 'Vinoth!', \nHow are you? \t Shall we meet tomorrow? \r Thanks ", 0, 567.5
109, "John", "[email protected]", "Hi 'John!' \nHow are you? \t Shall we meet tomorrow? \r Thanks ", 1, 105.41
[💙 Info - Jan 2, 2018, 4:52:28 PM]: userlist.csv
示例 3 - Swift - 启用严格验证
// Enable Strict Validation
CSVExport.export.enableStrictValidation = true
// Able to convert JSON string into CSV.
let string = "[{\"name\":\"vignesh\",\"email\":\"[email protected]\"},{\"name\":\"vinoth\",\"email\":\"[email protected]\"}]";
// Write File using CSV class object
let result1 = exportCSV("userlist", fields:["userid","name","email"], values:string);
XCTAssertEqual(false, result1.isSuccess)
if result1.isSuccess {
guard let filePath = result1.value else {
print("Export Error: \(String(describing: result1.value))")
return
}
print("File Path: \(filePath)")
} else {
print("Export Error: \(String(describing: result1.value))")
}
写入输出
Export Error: Optional("Expected 3 columns, But Parsed 2 columns on row 1")
示例 4 - Swift
// Read File
let fileDetails = readCSV(filePath);
// Use 'SwiftLoggly' pod framework to print the Dictionary
if fileDetails.allKeys.count > 0 {
loggly(LogType.Info, dictionary: fileDetails)
}
读取输出
[💙 Info - Jan 2, 2018, 4:52:21 PM]: {
"fields" : [
"userid",
"name",
"email",
"message",
"isValidUser",
"balance"
],
"rows" : [
{
"email" : "\"[email protected]\"",
"message" : "\"Hi 'Vignesh!' \\nhow are you? \\t Shall we meet tomorrow? \\r Thanks \"",
"userid" : 107,
"name" : "\"vignesh\"",
"isValidUser" : 1,
"balance" : 571.05
},
{
"email" : "\"[email protected]\"",
"message" : "\"Hi 'Vinoth!', \\nHow are you? \\t Shall we meet tomorrow? \\r Thanks \"",
"userid" : 108,
"name" : "\"vinoth\"",
"isValidUser" : 0,
"balance" : 567.5
},
{
"email" : "\"[email protected]\"",
"message" : "\"Hi 'John!' \\nHow are you? \\t Shall we meet tomorrow? \\r Thanks \"",
"userid" : 109,
"name" : "\"John\"",
"isValidUser" : 1,
"balance" : 105.41
}
],
"name" : "userlist.csv",
"divider" : ","
}
这将在 Mac OS X 和 iOS 的应用目录下生成 CSV 文件。
MacOS X 下的 CSV 文件将保存在 macOS 导出目录中(位于:/Library/Export)。iOS 下的 CSV 文件将保存在应用的文档目录下的 Exports 文件夹中。
配置
SwiftCSVExport 有一些可配置选项。
//Set the name of the csv file
CSVExport.export.fileName = "Sample" //default is "csvfile"
//Set the directory in which the csv files will be written
CSVExport.export.directory = "/Library/XXX-folder-name-XXX" //default is the standard exporting directory for each platform.
// Able to set strict validation while create a new CSV file.
CSVExport.export.enableStrictValidation = true
安装
CocoaPods
访问cocoapods.org网站上的“入门”选项卡。
要在项目中使用SwiftCSVExport,请将以下'Podfile'添加到您的项目中
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!
pod 'SwiftCSVExport'
然后运行
pod install || pod update
Carthage
要在项目中使用SwiftCSVExport,创建/更新项目中的'Cartfile.private'文件
// Require version 2.x
github "vigneshuvi/SwiftCSVExport"
然后运行
carthage update
Swift Package Manager for Vapor
您需要在'Package.swift'中的依赖项中添加,并通过终端注释使用Swift模块。
// Vapor
dependencies: [ .Package(url: "https://github.com/vigneshuvi/SwiftCSVExport.git", majorVersion: 2, minor: 0) ],
然后运行
vapor build || vapor xcode
// 导入头文件
import SwiftCSVExport
许可证
SwiftCSVExport 采用MIT许可证。