1

I want to export my contacts to an Excel file in android studio. Right now I access my contacts and save them to a table in Sqlite. I also have an export button, to export my data to an excel file. But how can I query my table and write the results to an Excel file?

btnExport.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

        CSVWriter writer = null;
        try
        {
            //read from db
            mydb=openOrCreateDatabase(DbName,Context.MODE_PRIVATE,null);
            Cursor crs=  mydb.rawQuery("Select * from tblContact",null);

            String[] array = new String[crs.getCount()];
            int i = 0;
            writer = new CSVWriter(new FileWriter("/sdcard/myfile.csv"), ',');

            while(crs.moveToNext()) {
                String uname = crs.getString(crs.getColumnIndex("FirstName"));
                array[i] = uname;
                i++;
                writer.writeNext(new String[]{array[i]});
            }
            writer.close();
            Toast.makeText(getApplicationContext(),"Exported",Toast.LENGTH_LONG).show();
            mydb.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
});
Kurt Van den Branden
  • 11,995
  • 10
  • 76
  • 85
Ali Saravani
  • 25
  • 1
  • 2
  • 7
  • 3
    Possible duplicate of [Android program to convert the SQLite database to excel](http://stackoverflow.com/questions/14049323/android-program-to-convert-the-sqlite-database-to-excel) – Maheshwar Ligade Jul 13 '16 at 09:43

0 Answers0