Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Generate CSV file from table values

Tags:

java

android

I have a database containing one table, i want to generate CSV file with values of this table.

Actually, I want to email this CSV file as an attachment. I know about sending file as an attachment in email intent(ACTION_SEND), but I don't know the procedure of creating or the method by which i can create CSV formatted file.

Please give me suggestions or ideas.

like image 357
Paresh Mayani Avatar asked Jan 08 '11 05:01

Paresh Mayani


2 Answers

You can use opencsv for this

Download the library from here:

http://sourceforge.net/projects/opencsv/

In this you can find jar file.

Inside your activity use this:

CSVWriter writer = null;
try 
{
    writer = new CSVWriter(new FileWriter("/sdcard/myfile.csv"), ',');
    String[] entries = "first#second#third".split("#"); // array of your values
    writer.writeNext(entries);  
    writer.close();
} 
catch (IOException e)
{
    //error
}
like image 66
Vikas Patidar Avatar answered Oct 02 '22 08:10

Vikas Patidar


THis might be helpfull.I needed ';' as seperator in between the feild values. Please use ',' accordingly for CSV generation.

Thanks, Darshan

private void exportTheDB() throws IOException
{
        File myFile;  
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
    String TimeStampDB = sdf.format(cal.getTime()); 

    try {

        myFile = new File(extStorageDirectory+"/Export_"+TimeStampDB+".csv");
        myFile.createNewFile();
        FileOutputStream fOut = new FileOutputStream(myFile);
        OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
        myOutWriter.append("Start time;End time;Elapse;Sports type");
        myOutWriter.append("\n");
        sampleDB = this.openOrCreateDatabase(DB_NAME,MODE_PRIVATE, null);

        Cursor c = sampleDB.rawQuery("SELECT * FROM  Sport_Records ", null);

        if (c != null) {
            if (c.moveToFirst()) {
                do {


                    String start_Time = c.getString(c.getColumnIndex("startTimeDate"));
                    String end_Time = c.getString(c.getColumnIndex("endTimeDate"));
                    String elapse_Time = calculateTimeDifferece(end_Time, start_Time);
                    String sport_Name = c.getString(c.getColumnIndex("label"));

                    myOutWriter.append(start_Time+";"+end_Time+";"+elapse_Time+";"+sport_Name);
                    myOutWriter.append("\n");
                }

                while (c.moveToNext());
            }

            c.close();
            myOutWriter.close();
            fOut.close();

        }
    } catch (SQLiteException se) 
    {
        Log.e(getClass().getSimpleName(),"Could not create or Open the database");
    }

    finally {

        sampleDB.close();

    }






}
like image 43
ReachmeDroid Avatar answered Oct 02 '22 07:10

ReachmeDroid