如何以.xlsx格式编写字符串?

问题描述 投票:-3回答:1

我已经尝试过.xls和.txt格式,它可以正常工作,但不能用于.xlsx格式。 iOS是否支持.xlsx格式?或者如果我缺少什么?

DispatchQueue.main.async(execute: {

let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)

let documentDirectory = paths[0]

let strBackupFileLocation = "\(documentDirectory)/\("\Log.xlsx")"

try? stringToWrite.write(toFile: strBackupFileLocation, atomically: true, encoding: .utf8)
})
swift nsdocumentdirectory
1个回答
0
投票

[我认为问题在于,xlsx是比txt(只是纯文本)或xls(是XML文件)更复杂的格式。正如您在一个问题中看到的那样:Looking for a clear description of Excel's .xlsx XML format xlsx格式是一个zip,您不能只向其中写入字符串。如果要将某些数据另存为xlsx文件,则必须使用一些可以处理它的库。例如,您可以使用XlsxReaderWriter,但我认为该库不允许您从头开始创建xlsx文件(您可以在TODO中看到:“从头开始创建电子表格文档”),因此您将需要一个空的xlsx文件包中的文件,您可以阅读,修改和保存。

//1 reading file from bundle
let documentPath = Bundle.main.path(forResource: "empty", ofType: "xlsx")
var spreadsheet: BRAOfficeDocumentPackage = BRAOfficeDocumentPackage.open(documentPath)

//2 get first worksheet in the workbook
var firstWorksheet: BRAWorksheet = spreadsheet.workbook.worksheets[0]

//3 add your string
worksheet.cellForCellReference("A1", shouldCreate: true).stringValue = "your string goes here"

//4 save file
if let fullPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last?.appending("/Log.xlsx") {
    spreadsheet.saveAs(fullPath)
}

将假定您的空xlsx文件名为empty.xlsx,并将其添加到应用包中。另外,请记住XlsxReaderWriter是一个Objective-C库,因此您将需要bridge header file。如果您不熟悉在Swift应用程序中使用Objective-C,则可以在文章Importing Objective-C into Swift中阅读更多内容。

© www.soinside.com 2019 - 2024. All rights reserved.