「SwiftUI」生成导出CSV文件

导出用户数据等功能

Posted by Jiaolong on 2022/04/06

#

func exportForCSV() {
    do {
        let csv = try! CSVWriter(stream: .toMemory())
        // Write a row
        try! csv.write(row: ["row1", "row2", "row3"])
        // Write fields separately
        let folders = folderStore.getAll()
        for folder in folders {
            let groups = folder.getAllGroup()
            for group in groups {
                let items = group.getAllItems()
                for item in items {
                    csv.beginNewRow()
                    try! csv.write(field: "\(folder.name!)")
                    try! csv.write(field: "\(group.name!)")
                    try! csv.write(field: "\(item.name!)")
                    try! csv.write(field: "\(item.price!)")
                    try! csv.write(field: "\(item.detail!)")
                    try! csv.write(field: "\(item.rate)")
                    try! csv.write(field: "\(item.mainDate!.toString())")
                    try! csv.write(field: "\(item.url!)")
                    try! csv.write(field: "\(item.getTagNames())")
                    if item.goalName != "" {
                        try! csv.write(field: "\(item.goalName!)")
                        try! csv.write(field: "\(item.goalDate!.toString())")
                    }else{
                        try! csv.write(field: "")
                        try! csv.write(field: "")
                    }
                    try! csv.write(field: "\(item.memo!)")
                    
                    try! csv.write(field: "\(TimeLineHelper.getTimeData(data: item.timeLine!))")
                    try! csv.write(field: "\(item.isLike)")

                    try! csv.write(field: "\(item.isArchive)")
                    try! csv.write(field: "\(item.archiveMemo ?? "")")
                    try! csv.write(field: "\(item.isHide)")

                }
            }
        }

        
        csv.stream.close()
        
        // Get a String
        let csvData = csv.stream.property(forKey: .dataWrittenToMemoryStreamKey) as! Data
        let csvString = String(data: csvData, encoding:  .utf8)!
        
        
        print(csvString)
        let enc = CFStringConvertEncodingToNSStringEncoding(UInt32(CFStringEncodings.GB_18030_2000.rawValue))

        let fileName = "MyThings.csv"
        let path = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName)

        do {
            try csvString.write(to: path!, atomically: true, encoding:  String.Encoding(rawValue: enc))
        } catch {
            print("Failed to create file")
            print("\(error)")
        }
        print(path ?? "not found")

        var filesToShare = [Any]()
        filesToShare.append(path!)


        let activityViewController = UIActivityViewController(activityItems: filesToShare, applicationActivities: nil)
        
        let viewController = Coordinator.topViewController()
        activityViewController.popoverPresentationController?.sourceView = viewController?.view
        viewController?.present(activityViewController, animated: true, completion: nil)
      
    } catch {
        print("Failed to create file")
        print("\(error)")
    }
    
    
}