csv - 在 Kotlin 中使用几列将对象写入 csv 文件
问题描述
我在将对象输入 csv 文件时遇到问题。我以三种方式执行此操作,但每种方式都将对象的所有字段放入 csv 文件的一列中。如何更正代码以使对象的每个字段都在 csv 文件的一列中?
val csvWrite = CSVWriter(FileWriter("${requireActivity().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)}/Export/inventory${date}.csv")) //First way
val writer = BufferedWriter(FileWriter("${requireActivity().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)}/Export/inventory${date}.csv"))
val csvPrinter = CSVPrinter(writer,
CSVFormat.DEFAULT.withHeader
("Id", "WhsId", "Date", "UserId", "ProductId", "Quantity", "Batch", "Expiration date", "Production date")) //Second way
val csvWriter = CSVWriterBuilder(writer)
.withSeparator(CSVWriter.DEFAULT_SEPARATOR)
.withQuoteChar(CSVWriter.NO_QUOTE_CHARACTER)
.withEscapeChar(CSVWriter.DEFAULT_ESCAPE_CHARACTER)
.withLineEnd(CSVWriter.DEFAULT_LINE_END)
.build() //Third way
inventoryLocalViewModel.positionList
.onEach {
var list = it
for(item in list) {
val arrStr = arrayOf<String>(item?.id.toString(), item?.whsId.toString(), item?.date.toString(), item?.userId.toString(), item?.productId.toString(), item?.quantity.toString(), item?.batch.toString(), item?.expireDate.toString(), item?.prodDate.toString())
val stt4 = Arrays.asList(item?.id, item?.whsId, item?.date, item?.userId, item?.productId, item?.quantity, item?.batch, item?.expireDate, item?.prodDate)
csvWrite.writeNext(arrStr) //First way
csvWriter.writeNext(arrStr) // Second way
csvPrinter.printRecord(stt4) // Third way
}
}
.launchIn(viewLifecycleOwner.lifecycleScope)
csvWrite.close() //First way
csvWriter.flush() // Second way
csvWriter.close()
writer.close() // Second way
csvPrinter.flush() // Third way
csvPrinter.close() // Third way
解决方案
推荐阅读
- cobol - COBOL 代码不会编译和创建可执行文件
- python - 以用户为外键的模型上的 Django 查询集
- soap - 是否有 Alpakka SOAP 支持?
- python - 如何舍入并与模型中的 PyMC3 先前参数进行比较?
- javascript - 澄清重新:Vue.js 动作/突变
- facebook - FB 提及在使用 /{comment-id}/comments 时不起作用
- python - 将多个输入传递到 Keras 模型时出错
- json - jinja2 动态导航到 json 对象
- wpf - 使用 WiX 安装程序更新时如何更新固定到任务栏的应用程序图标
- jquery - 通过 AJAX 发送图像文件。request.FILES 为空?