Exporting SQLite Database to csv file in android

前端 未结 3 672
半阙折子戏
半阙折子戏 2020-11-29 03:54

I am trying to export SQLite data to SD card in android as a CSV file on a directory.

So i have tried this method below and apparently it only shows this text printe

3条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 04:23

    Thanks for your suggestions guys which led me to this answer:

    private void exportDB() {
    
            DBHelper dbhelper = new DBHelper(getApplicationContext());
            File exportDir = new File(Environment.getExternalStorageDirectory(), "");
            if (!exportDir.exists())
            {
                exportDir.mkdirs();
            }
    
            File file = new File(exportDir, "csvname.csv");
            try
            {
                file.createNewFile();
                CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
                SQLiteDatabase db = dbhelper.getReadableDatabase();
                Cursor curCSV = db.rawQuery("SELECT * FROM contacts",null);
                csvWrite.writeNext(curCSV.getColumnNames());
                while(curCSV.moveToNext())
                {
                    //Which column you want to exprort
                    String arrStr[] ={curCSV.getString(0),curCSV.getString(1), curCSV.getString(2)};
                    csvWrite.writeNext(arrStr);
                }
                csvWrite.close();
                curCSV.close();
            }
            catch(Exception sqlEx)
            {
                Log.e("MainActivity", sqlEx.getMessage(), sqlEx);
            }
    }
    

提交回复
热议问题