문제

I want to export some fields from a table in my SQLite database in CSV format. I'm using the library opencsv-2.4. Works, but all the columns of the table are stored in a single column of the spreadsheet instead must 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);
}

}

도움이 되었습니까?

해결책

You need to use a separator for your columns.

Use this syntax:

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

Instead of:

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

This sets a comma (,) as the field separator and a newline (\n) as the line terminator

Or simply

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

This sets a comma (,) as the field separator.
Excel uses a semicolon (;).
Other software might use pipe (|) or tab (\t) or ...

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top