如何使用Swift创建CSV文件

sulc1iza  于 2022-12-06  发布在  Swift
关注(0)|答案(2)|浏览(164)

在我创建的用于收集Apple铅笔输入数据的应用程序中,我尝试将数据导出到CSV文件中。但到目前为止,我只创建了一个记录时间长度的列。我想添加另一个列来记录Apple铅笔的力。
这就是我一直努力要做的:

var patientsData:[Dictionary<String, AnyObject>] = Array()
var dct = Dictionary<String, AnyObject>()

// MARK: CSV writing
func createCSVX(from recArray:[Dictionary<String, AnyObject>]) {
var csvString = "\("Time")\n"
dct.updateValue(TestDraw.time as AnyObject, forKey: "T")
csvString = csvString.appending("\(String(describing: dct["T"]))\n")
patientsData.append(dct)
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")
    }

}

我知道我可以编写另一个函数来创建另一个CSV文件,其中有一列记录力,但我希望将它们记录在一个电子表格中。
另外,有人知道如何删除创建的CSV文件中的“可选”吗?
这是我根据其中一个答案所做的尝试。

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)

}

3gtaxfhh

3gtaxfhh1#

教程复制自https://iostutorialjunction.com/2018/01/create-csv-file-in-swift-programmatically.html
步骤1:

创建一个名为“employeeArray”的数组,它将把所有雇员的记录作为键值对象存储起来。

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

第2步:现在我们有了数据,是时候使用swift编程创建CSV(逗号分隔值)文件了。为此,我们将遍历“employeeArray”中的记录,并将它们添加到一个字符串中。然后,我们将把这个字符串写入应用程序的文档目录中。所有的东西都放在名为“createCSV”的不同函数中,下面是相同的代码

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

    }

步骤3:最后我们将从“viewDidLoad”调用函数。

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

    }
 }
bvjxkvbb

bvjxkvbb2#

上面的回答很好,做了一个小的修改来处理数据中的特定示例。你可以根据需要修改单个组件,删除逗号,修剪UUID等。注意,这个解决方案使用存储在Core Data对象列表中的事务。我还打印了数据文件的位置,这样你就可以在模拟器中检查它。

func createCSVFile() {
        var csvString = "id,name,description,category,date,type,receipt,amount\n"
        for trans in transactions {
            let transID = trans.id!.debugDescription.split(separator: "-")[0].replacingOccurrences(of: ")", with: "")
            let transName = trans.name!
            let transDesc = trans.desc!.replacingOccurrences(of: ",", with: "-")
            let transCat = trans.category!
            let transDate = trans.date!
            let transType = trans.type!
            
            var transReceipt = "None"
            if trans.receipt == nil {
                transReceipt = "Present"
            }
            let transAmount = trans.amount
            let dataString = "\(transID),\(transName),\(transDesc),\(transCat),\(transDate),\(transType),\(transReceipt),\(transAmount)\n"
            print("DATA: \(dataString)")
            csvString = csvString.appending(dataString)
        }

        let fileManager = FileManager.default
        do {
            let path = try fileManager.url(for: .documentDirectory, in: .allDomainsMask, appropriateFor: nil, create: false)
            print("PATH: \(path)")
            let fileURL = path.appendingPathComponent("CSVData.csv")
            try csvString.write(to: fileURL, atomically: true, encoding: .utf8)
        } catch {
            print("error creating file")
        }
    }

相关问题