How does one export a Room table to a CSV format?

前端 未结 3 1040
广开言路
广开言路 2021-02-04 22:29

I have an app right now that stores data in a Room database using several entities. What I need is to take the contents of a table, convert the data into a CSV format, and then

3条回答
  •  青春惊慌失措
    2021-02-04 23:33

    It's really easy to export Room DB table to CSV file in Kotlin using kotlin-csv library.

    Just get the list of DB table objects:

    @Dao
    interface DirectorDao {
        @get:Query("SELECT * FROM director ORDER BY full_name ASC")
        val allDirectors: LiveData>
    }
    

    Then user CSV writer to write into the file by going through all list items and adding the column values to CSV rows, one by one, like this:

    csvWriter().open(csvFile) {
        // Header
        writeRow(listOf("[id]", "[name]", "[age]"))
    
        directorDao.allDirectors.value.forEachIndexed { index, director ->
            writeRow(listOf(index, director.fullName, director.age))
        }
    }
    

    I explain the whole flow here.

提交回复
热议问题