How to export data as a csv file?

I am using Xcode 10, swift 5.0. I want to export two variables into a csv file, which should be like this:
54%20PM

How to do this?

1 Like

Hi @feanor, I would try creating a path to the file in a temporary directory, then with the variables that contain the text I’d loop through the list to create a new line of data for each row and then append it to the file. Then write the file to the path that was created in the temporary directory. Afterwards, with exporting you can possibly use a UIActivityController to present the file.

Best,
Gina

Thank you for the suggestion.

func createCSVX(from recArray:[Dictionary<String, AnyObject>]) {
var csvString = "\("Time"),\("Force")\n"

dct.updateValue(TestDraw.time **as** AnyObject, forKey: "T")

dct.updateValue(TestDraw.force **as** AnyObject, forKey: "F")

patientsData.append(dct)

csvString = csvString.appending("\(String(describing: dct["T"])), \(String(describing:   dct["F"]))\n")

let fileManager = FileManager.default

do {

let path = try fileManager.url(for: .documentDirectory, in: .allDomainsMask, appropriateFor: nil , create: false )

let fileURL = path.appendingPathComponent("TrailTime.csv")

try csvString.write(to: fileURL, atomically: true , encoding: .utf8)
} catch {

print("error creating file")

}

print(TestDraw.force)

}

This is what I have tried, but unfortunately, the data in Force all go​ into the Time column.
49%20AM
Could you please tell me why?

I am running it on a simulator so the force is all going to be zero.

@feanor There’s a lot of unexplained code there, most of which doesn’t seem to be contributing to the CSV, so I’m going to ignore that. There may be a compelling reason for your data to be an array of dictionarys rather than structs, but I’d encourage you to look into that (to avoid the uncertainty of whether the dictionary contains a value for a given key).

You don’t ever make use of recArray, which seems to be the thing containing the data. I’d suggest this:

func createCSVX(from recArray:[Dictionary<String, AnyObject>]) {

	// No need for string interpolation ("\("Time"),\("Force")\n"), just say what you want:
	let heading = "Time, Force\n"

	// For every element in recArray, extract the values associated with 'T' and 'F' as a comma-separated string.
	// Force-unwrap (the '!') to get a concrete value (or crash) rather than an optional
	let rows = recArray.map { "\($0["T"]!),\($0["F"]!)" }

	// Turn all of the rows into one big string
	let csvString = heading + rows.joined(separator: "\n")

	do {

		let path = try FileManager.default.url(for: .documentDirectory,
											   in: .allDomainsMask,
											   appropriateFor: nil,
											   create: false)

		let fileURL = path.appendingPathComponent("TrailTime.csv")
		try csvString.write(to: fileURL, atomically: true , encoding: .utf8)
	} catch {
		print("error creating file")       
	}
}

Thank you very much. The problem is solved

hi @feanor,
glad to hear you got it resolved,
The problem you faced was with getting dictionary values, the newer API now also includes a default value, so you can use that to get a value than an optional. Also in Swift 5 you have compactMapValues that can remove nils and provide you with a <String, String> if that’s what you are after.

cheers,

SpatialKey requires data to be uploaded and imported by way of a CSV file before a dataset can be imported. We have tried to make the import process as fun and simple as possible, but SpatialKey cannot help you get your data into CSV format. In many cases that precious data you need access to will be locked away inside of a database. There are many types of databases, and most of them have capabilities to help get your data exported into a CSV format but they are usually specific to the database in question.

This goal of this article is to examine how to get data into a CSV format from many of the more poplar databases and database management systems on the market today. If you do not have access to the database where your data resides and have a database administrator or IT staff that generates your reports for you, pass on the link to this article when requesting data for SpatialKey as it may save them some time as well.

Please note that this article deals with usage of the Structured Query Language (SQL) commands needed to run against a database and is intended for users who are familiar with SQL and tools for the database they commonly use.

Microsoft Access:

Microsoft Access is a popular file based database used typically by small organizations with limited numbers of users and by individuals as well. MS Access data can be accessed using the MS Access application in a visual way as well as through traditional SQL based approaches. As MS Access has recently undergone a major user interface change, we will explore both the 2007 and 2003 versions of the application (if you are working with an older version, similar techniques should also be available).

Access 2007:
In the first figure (1.1) you can see I have opened up the standard example database that comes with MS Access (called Northwind). I have also selected the query called “Top Ten Orders by Sales Amount”. To this query, I have added customer address information since SpatialKey loves data that contains temporal (time and date) and geospatial (data that can be translated to a location) data.

From here I can easily export the results to a CSV file:

  1. Click on the table or query to export from (in this example “Top Ten Orders by Sales Amount” on the left)

  2. Click the “External Data” tab at the top of the window

  3. In the “Export” section click “Text File” and a wizard will appear

  4. Choose a location for the exported CSV and name your file (make sure the file ends with a .csv extension)

  5. Click OK

  6. On the next screen be sure the “Delimited” option is selected

  7. Click the “Advanced…” button in the lower left of the window

  8. SpatialKey stores its data as Unicode UTF-8, we need to ensure that the data is exported in this format

  9. Click the drop-down box next to Code-Page

  10. Choose Unicode (UTF-8) in the options list

  11. Click OK

  12. Back at the Export Text window click “Next”

  13. Be sure “Comma” is selected as the delimiter and Text Qualifier is a double quote: “

  14. Click the checkbox “Include Field Names on First Row” (should be selected)

  15. Click “Next”

  16. Verify the file name and location and click “Finish”

  17. The final screen of the wizard gives you the option to save the steps allowing for easy re-exporting of the data in the future. If you anticipate needing to update the data in SpatialKey go ahead and check the checkbox to save some time in the future. Close the window when finished.

If you open the file in a text editor, you should see something like this:

  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

  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 a different function named as '[createCSV, below is the code for the same

  3. Finally, we will call our function from “viewDidLoad”. Below is the complete code

Thank you for answering!

This topic was automatically closed after 166 days. New replies are no longer allowed.