首页 > 解决方案 > 在 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

标签: csvkotlinopencsv

解决方案


推荐阅读