10

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.

Paresh Mayani
  • 127,700
  • 71
  • 241
  • 295

5 Answers5

33

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
}
Vikas Patidar
  • 42,865
  • 22
  • 93
  • 106
  • i have visited the link you have provided, but i didnt come to know how do i include this in my android application. please let me know, Thanx for your quick response – Paresh Mayani Jan 08 '11 at 06:19
  • i think you mean that i should include this CSVWriter class and then i should play with this CSVWriter class, is it so ? – Paresh Mayani Jan 08 '11 at 06:25
  • thanx vikas, i already implemented and got the same solution as you mentioned. Btw, thanx for your timely support. – Paresh Mayani Jan 08 '11 at 13:09
  • @VikasPatidar How can I continously save data? I have data generated continuously and apparently until I don't call `close()` it doesnt save – Tina J Aug 29 '16 at 18:54
  • I had a Gradle warning for CSVWriter's commons-logging dependency when adding com.opencsv:opencsv:4.0. – LordParsley Aug 15 '17 at 09:17
  • I cannot get my app to successfully use proguard with open csv – Carson Holzheimer Mar 04 '19 at 22:53
13

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();

    }






}
ReachmeDroid
  • 959
  • 1
  • 14
  • 17
3

This looks really promising. It will take any Java object and convert it to a CSV file:

http://supercsv.sourceforge.net/

It also might be possible to retrieve the data from the database in CSV format.

jamesmortensen
  • 33,636
  • 11
  • 99
  • 120
1

Adding to @Cocos2dx answer:

When querying from db you may have null fields, in my case i use a Controller to fetch the data in an object list, but either if you don`t you should check for null or empty values and proper format them (or they can make your table look weird):

String[] details = { 
        replaceNull(someObject.getId()),
        replaceNull(someObject.getName())
};


public static String replaceNull(String input) {
    return ((input == null || input.isEmpty()) ? " " : input);
}

writer.writeNext(details);
Jared Rummler
  • 37,824
  • 19
  • 133
  • 148
Renato Probst
  • 5,914
  • 2
  • 42
  • 45
0

In case of using Kotlin, I recommend kotlin-csv library.

Just get the list of DB table objects, go through all of them and add the column values to CSV rows, one by one, like this:

csvWriter().open(csvFile) {
    // Header
    writeRow(listOf("[id]", "[name]", "[age]"))

    peopleList.forEachIndexed { index, person ->
        writeRow(listOf(index, person.fullName, person.age))
    }
}

I explain the whole process of creating csv file here.

lomza
  • 9,412
  • 15
  • 70
  • 85