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