Introduction to how to create CSV file in swift programmatically
As the heading of this tutorial says, we are going to learn how to create csv file in swift programmatically. CSV(comma separated values) or excel files as they are commonly known are not a difficult task in iOS app development using swift. In this post, we will learn the code for creating CSV(comma separated values) file in swift programmatically and save it to document directory. If you are looking for objective c version then please follow the given below link
Steps to create csv file
Step 1: Create an array, named as “employeeArray” which will store all our records for the employees as key value objects. Also we will add dummy data to the newly created array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ViewController: UIViewController { | |
var employeeArray:[Dictionary<String, AnyObject>] = Array() | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// Do any additional setup after loading the view, typically from a nib. | |
for i in 1...10 { | |
var dct = Dictionary<String, AnyObject>() | |
dct.updateValue(i as AnyObject, forKey: "EmpID") | |
dct.updateValue("NameForEmplyee id = \(i)" as AnyObject, forKey: "EmpName") | |
employeeArray.append(dct) | |
} | |
} | |
} |
Step 2: Now we have data with us, and its time to create CSV(comma separated values) file using swift programmatically. For this we will loop through our records in “employeeArray” and append them in a string. Then we will write this string to our document directory of the app. All the stuff goes in different function named as “createCSV”, below is the code for the same
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func createCSV(from recArray:[Dictionary<String, AnyObject>]) { | |
var csvString = "\("Employee ID"),\("Employee Name")\n\n" | |
for dct in recArray { | |
csvString = csvString.appending("\(String(describing: dct["EmpID"]!)) ,\(String(describing: dct["EmpName"]!))\n") | |
} | |
let fileManager = FileManager.default | |
do { | |
let path = try fileManager.url(for: .documentDirectory, in: .allDomainsMask, appropriateFor: nil, create: false) | |
let fileURL = path.appendingPathComponent("CSVRec.csv") | |
try csvString.write(to: fileURL, atomically: true, encoding: .utf8) | |
} catch { | |
print("error creating file") | |
} | |
} | |
Step 3: Finally we will call our function from “viewDidLoad”. Below is the complete code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ViewController: UIViewController { | |
var employeeArray:[Dictionary<String, AnyObject>] = Array() | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
for i in 1...10 { | |
var dct = Dictionary<String, AnyObject>() | |
dct.updateValue(i as AnyObject, forKey: "EmpID") | |
dct.updateValue("NameForEmplyee id = \(i)" as AnyObject, forKey: "EmpName") | |
employeeArray.append(dct) | |
} | |
createCSV(from: employeeArray) | |
} | |
func createCSV(from recArray:[Dictionary<String, AnyObject>]) { | |
var csvString = "\("Employee ID"),\("Employee Name")\n\n" | |
for dct in recArray { | |
csvString = csvString.appending("\(String(describing: dct["EmpID"]!)) ,\(String(describing: dct["EmpName"]!))\n") | |
} | |
let fileManager = FileManager.default | |
do { | |
let path = try fileManager.url(for: .documentDirectory, in: .allDomainsMask, appropriateFor: nil, create: false) | |
let fileURL = path.appendingPathComponent("CSVRec.csv") | |
try csvString.write(to: fileURL, atomically: true, encoding: .utf8) | |
} catch { | |
print("error creating file") | |
} | |
} | |
} |
Note: Please remove “comma” for your data in order to create accurate CSV.
Where to go from here:
In this post, we learned how we can create a csv(Comma separated file) file programmatically in swift. If you have any query then please free to ask using our comment section and we will respond back to you as soon as we can. Thank you 🙂
Pingback: Create csv file in iPhone programmatically - iOSTutorialJunction