Export Android data to csv

I want to export some fields from a table in my SQLite database in format CSV. I am using the library opencsv-2.4. Works, but all columns of the table are stored in one column of the spreadsheet, but should be separated. This is my method:

  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 = mHelper.getReadableDatabase();
    Cursor curCSV = db.rawQuery("SELECT * FROM Table",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);
}

}

+4
source share
1 answer

You need to use a separator for your columns.

Use this syntax:

CSVWriter writer = new CSVWriter(new FileWriter(file), ",", "", "\n");

Instead:

CSVWriter csvWrite = new CSVWriter(new FileWriter(file));

This sets the comma ( , ) as the field delimiter and the new line ( \ n ) as the line delimiter

Or simply

CSVWriter writer = new CSVWriter(new FileWriter(file), ",");

(,).
Excel (;).
pipe (|) (\t) ...

+1

Source: https://habr.com/ru/post/1535403/


All Articles