Giter Club home page Giter Club logo

swiftcsvexport's Introduction

CSV Swift Version Language Swift Swift Package Manager compatible Carthage compatible

SwiftCSVExport

Swift CSV Export is lightweight & rich features framework and it helpful to create, read and write CSV files in simple way. It supports both Objective-C and Swift projects.

Features

  • Support swift 4, 4.2 and 5 and latest Xcode(12)
  • Able to give CSV file name, headers and rows using property keys.
  • Able to convert JSON string into CSV.
  • Able to Read the CSV file and convert to NSDictionary.
  • Enable/Disable strict validation while write CSV file.
  • Able to Read the CSV file and convert to CSV class(Object Oriented Approach).
  • Support CocoaPods, mac OS and Vapor framework(Swift Package Manager).
  • Able to encoding CSV based on String.Encoding Type(utf8, ascii, unicode, utf16, etc) Refer: String.Encoding.
  • Able to view the exported CSV documents in iOS Files app by enabling the configuration in your project.
  • Handled the punctuation(\n, \t, \t, and ,) characters in CSV file.

Swift Version

Supported swift 4, 4.2 and 5 and latest 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 import headers

First thing is to import the framework. See the Installation instructions on how to add the framework to your project.

Refer iOS Examples:Here. Refer Mac Examples:Here.

//iOS - Objective-C
@import SwiftCSVExport;

//iOS - Swift
import SwiftCSVExport

//macOS - Old swift version < 4
import SwiftCSVExportOSX 

//macOS - New swift version > 4
import SwiftCSVExport

Configuration

  • Add following keys in your project .plist file to view CSV exported CSV documents in iOS Files app.
Bundle display name - "APPLICATION NAME"
Application requires iPhone environment - YES
Supports opening documents in place - YES
Application supports iTunes file sharing - YES

Examples:

Example 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);

Example 2 - Swift - Object Oriented Approach

// 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))")
}


Write & Read Output:

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

Example 3 - Swift - Enable Strict Validation

// 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))")
}

Write Output:

Export Error: Optional("Expected 3 columns, But Parsed 2 columns on row 1")

Example 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)
}

Read Output:

[πŸ’™ 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" : ","
}

That will create a CSV file in the proper directory on both OS X and iOS.

OS X CSV files will be created in the OS X Exports directory (found under: /Library/Exports). The iOS CSV files will be created in your apps document directory under a folder called Exports.

Configuration

There are a few configurable options in 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

Installation

CocoaPods

Check out Get Started tab on cocoapods.org.

To use SwiftCSVExport in your project add the following 'Podfile' to your project

  source 'https://github.com/CocoaPods/Specs.git'
  platform :ios, '8.0'
  use_frameworks!

  pod 'SwiftCSVExport'

Then run:

pod install || pod update

Carthage

To use SwiftCSVExport in your project create/update 'Cartfile.private' file into your project

// Require version 2.x

github "vigneshuvi/SwiftCSVExport"

Then run:

carthage update

Swift Package Manager for Vapor

You need to add to dependencies in your 'Package.swift' and fetch Swift module using terminal comment.

// Vapor

dependencies: [ .Package(url: "https://github.com/vigneshuvi/SwiftCSVExport.git", majorVersion: 2, minor: 0) ],

Then run:

vapor build || vapor xcode

// Importing header

import SwiftCSVExport

License

SwiftCSVExport is licensed under the MIT License.

Contact

Vignesh Kumar

swiftcsvexport's People

Contributors

jeehut avatar norbertovasconcelos avatar vignesh-kumar-p avatar vigneshuvi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

swiftcsvexport's Issues

SwiftPM in Xcode 12: Failed to resolve dependencies.

When adding this library to an iOS project via Xcodes SwiftPM functionality, I get this error:

because SwiftCSVExport >=1.0.0 contains incompatible tools version and root depends on SwiftCSVExport 2.3.0..<3.0.0, version solving failed.

Strange Formatting

First Last Company Address1 Address2 City State Postalcode Country Sender Frontimage Backtext Accentimage Backimage Β  Β 
Loma Linda Back Image Back Text 2nd Floor Mary Ann Missouri 64804 Fuller 4 States Printing Accent Image Record ID Rusty 12345678 Front Image United States 1234 Appaloosa Way

I am getting strange formatting

How are you handling quotes and commas?

exportCSV:
Quotes in values are written as they are, which causes problems when opening up in Excel.
Ideally, any " found in values should be turned into "".

readCSV:
Any row with a value that contains a comma seems to be ignored.
(But values with commas do get written fine by exportCSV.)

Strange ordering of fields

Am I doing something wrong here, because this code:

let path = CSVExport.export.exportCSV(filename,
                                  fields: ["a", "b", "c"],
                                  values: [["a": 1, "b": 2, "c": 3],
                                           ["a": 4, "b": 5, "c": 6],
                                           ["a": 7, "b": 8, "c": 9]])

...produces this result:

a,b,c
2,1,3
5,4,6
8,7,9

Change cell properties

Is there a way to change a specific cell's background color and text color and/or text font size?

Adding Two Spaces

Whenever I am writing a string in a column it adds extra two spaces before that.

How to make header as vertical and values as side by side

in your current case you have handled csv which exports data in horizontal way like header1, header2 etc and then values followed below like value1,value2 etc. Now how can i achieve it like this header 1 -> value 1, header2->value2 etc

Cocoa pod not working.

Might be there is an issue with the current pod. it is not working on the project. See below image.
the pod is just adding .h file source file is missing.
screen shot 2017-07-12 at 12 39 27 pm

String quotes

Hi,
First of all great library. I am using it for some time for my application. In last version strings didn't have quotes around them, and in this new version, there are. Can you make them optional with some parameter for settings?

I changed: let fString = "(string)" to get rid of quotes.

Thanks

Support Turkish Characters

It's not supporting Turkish characters. And also CVS format is not correct. I'm using Excel 2019.

image

This is the Turkish characters. Δ±, ğ, Δ°, Ğ, Γ§, Γ‡, ş, Ş, ΓΆ, Γ–, ΓΌ, Ü

Using ; as divider

Hi, first of all thanks for your amazing work.

I only have one problem, I cannot set the field divider to semicolon (;) instead of commas.

I've tried:

  let writeCSVObj = CSV()
  writeCSVObj.delimiter = DividerType.semicolon.rawValue
  writeCSVObj.rows = data
  writeCSVObj.fields = headers as NSArray
  writeCSVObj.name = "ExportTest"

as well as:

  let writeCSVObj = CSV()
  writeCSVObj.delimiter = ";"
  writeCSVObj.rows = data
  writeCSVObj.fields = headers as NSArray
  writeCSVObj.name = "ExportTest"

but the output file will always have commas as field dividers. Am I missing something?

Quotes in string

When export the file, in the first row every string has '' quotes around it. Is there anyway we can stop this?

StringTest shows as 'StringTest' in the first row.

Won't build with Xcode 10.2 - Swift 3.0

Getting the following for SwiftCSVExportOSX after the Xcode update yesterday (3/26/19):

error: SWIFT_VERSION '3.0' is unsupported, supported versions are: 4.0, 4.2, 5.0. (in target 'SwiftCSVExportOSX')

How to handle comma in address ?

Hi,

after I export an address string to excel I found it split it into 2 column.
example my address is "No 10-20, Tmn Kinrara" but in excel it make "No 10-20" into 1 column and make "Tmn Kinrara" inside another column.

anyway to solve it ?

Directory for CSV file does not get created in IOS

I am developing an iPhone app using Xcode 9 and Swift 4. I have followed your installation instructions meticulously and I have attempted to create a CSV file. When I run the app the cdv file never gets populated into the directory in the app documents folder . I reviewed the CSVExport.swift file and I see the following code πŸ‘

///get the default CSV directory

class func defaultDirectory() -> String {
    var path = "/SampleSwift"
    let fileManager = FileManager.default
    #if os(iOS)
        let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
        path = "\(path[0])/Exports"
    #elseif os(OSX)
        let urls = fileManager.urls(for: .libraryDirectory, in: .userDomainMask)
        if let url = urls.last?.path {
            paths = "\(url)/Exports"
        }
    #endif
    if !fileManager.fileExists(atPath: path) && path != ""  {
        do {
            try fileManager.createDirectory(atPath: path, withIntermediateDirectories: false, attributes: nil)
        } catch _ {
        }
    }
    return path
}

I have an iPhone 7 plus connected as a test device. I never receive any runtime errors. The console displays the following path for the userlist1.csv file πŸ‘

/var/mobile/Containers/Data/Application/13DB9A0A-774C-45B0-A753-62FF8C56CF11/Documents/Exports/userlist1.csv

How do I get access to that file ? It never gets populated into the apps documents folder and the Exports folder never gets created.

I would appreciate any assistance you can offer .
thanks !
Tom

Cannot find 'exportCSV' in scope

I was able to add the Package Manager but I am getting this error:

let result = exportCSV(writeCSVObj); --> Cannot find 'exportCSV' in scope

I have already imported SwiftCSVExport

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.