Exporting Data Via CSV File
I think this CodableCSV project will be a really good starting point for you.
Here's the end of my modified createCsv()
:
let myRows = [
["Quanity", "Item", "Cost", "Total", "Total (USD)"],
[sCount, barName, sCost, sTotal, newTotal]
]
do {
let string = try CSVWriter.encode(rows: myRows, into: String.self)
print(string)
return MessageDocument(message: string)
} catch {
fatalError("Unexpected error encoding CSV: \(error)")
}
When I click on the 'Export' button, I see, from that print statement:
Quanity,Item,Cost,Total,Total (USD)
"1,600",ChocoBar,€4.95,"€7,920.00","$8,954.27"
You're going to need to be deliberate about adding title
, subTitle
, "Sale in Dollars"
because the rows they're on need to have the same number of columns as your data—CSV isn't Excel in this regard; where in Excel you can put data in any cell, no imposed structure—so something like:
let myRows = [
["Henry's Chocolate Sales Frankfurt", "", "", ""], // 3 empty (placeholder) columns
...
]
How to create a CSV file using Swift
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
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
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
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")
}
}
}
How to save and get CSV file attachment from Email in IOS
I have successfully done saving CSV file into iCloud using below link
Save iOS 8 Documents to iCloud Drive
I have used below link for retrieving the iCloud Files/Documents.
https://github.com/iRareMedia/iCloudDocumentSync
Export/Import Documents can be referred using below link
Export & Import Documents using iCloud in IOS
SwiftUI - Exporting Core Data to CSV file - cannot iterate through entity
Eureka! :)
I was missing a @FetchRequest:
@FetchRequest(entity: NPTransaction.entity(), sortDescriptors: []) var transactions: FetchedResults<NPTransaction>
Full code below. Maybe it will be useful for someone else.
import SwiftUI
struct SettingsView: View {
@FetchRequest(entity: NPTransaction.entity(), sortDescriptors: []) var transactions: FetchedResults<NPTransaction>
@State private var isShareSheetShowing = false
var body: some View {
NavigationView {
Button(action: shareButton)
{
HStack(alignment: .firstTextBaseline) {
Text("Export CSV")
.font(.headline)
Image(systemName: "square.and.arrow.up")
.font(.title)
}
}
}
.navigationBarTitle("Settings")
}
func shareButton() {
let fileName = "export.csv"
let path = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName)
var csvText = "Date,Type\n"
for transaction in transactions {
csvText += "\(transaction.date ?? Date()),\(transaction.type ?? "-")\n"
}
do {
try csvText.write(to: path!, atomically: true, encoding: String.Encoding.utf8)
} catch {
print("Failed to create file")
print("\(error)")
}
print(path ?? "not found")
var filesToShare = [Any]()
filesToShare.append(path!)
let av = UIActivityViewController(activityItems: filesToShare, applicationActivities: nil)
UIApplication.shared.windows.first?.rootViewController?.present(av, animated: true, completion: nil)
isShareSheetShowing.toggle()
}
}
struct SettingsView_Previews: PreviewProvider {
static var previews: some View {
SettingsView()
}
}
How to log sensor data and export to CSV?
All you have to do to create a CSV file is create a string with commas separating your columns, and newlines separating your rows, then write the string to a file.
let csvString = allData
.map { "\($0.x),\($0.y),\($0.z)" }
.joined(separator: "\n")
csvString.write(toFile: "some-file.csv", atomically: true, encoding: .utf8)
Related Topics
Enable Application Cache in Wkwebview
Clear Background for Form Sections in Swiftui
Uitableview Dynamic Cell Heights Only Correct After Some Scrolling
How to Retrieve a File Using Wkwebview
Ib_Designable, Ibinspectable -- Interface Builder Does Not Update
How to Set Device (Ui) Orientation Programmatically
How to Maintain Presenting View Controller's Orientation When Dismissing Modal View Controller
Xcode - Mpnowplayinginfocenter Info Is Not Displayed on iOS 8
Wkwebview Content Loaded Function Never Get Called
Xcode: "This App Could Not Be Installed at This Time."
Can Not Save File Inside Tmp Directory
Use Didselectrowatindexpath or Prepareforsegue Method for Uitableview
Programmatically Dial a Phone Number and Pass Dtmf Using the iPhone Sdk
Kvo and Arc How to Removeobserver
How to Prevent Keyboard Push Up Webview at iOS App Using Phonegap