samedi 18 avril 2015

How to export data from SQLite into excel in android?

I am trying to export data from SqLite DB to excel file. I want to save it to sd card. I am trying the following code and the file is not generating. Although through the file manager I am able to see the file but while connecting it through USB cable I am not find the folder in my PC.


i am using jxl.jar lib


final String fileName = "Userlist.xls";



//Saving file in external storage
File sdCard = Environment.getExternalStorageDirectory();

File directory = new File(sdCard.getAbsolutePath() + "/My sheet");

//create directory if not exist
if(!directory.isDirectory()){
directory.mkdirs();
}

//file path
File file = new File(directory, fileName);

WorkbookSettings wbSettings = new WorkbookSettings();
wbSettings.setLocale(new Locale("en", "EN"));

WritableWorkbook workbook;

try {
workbook = Workbook.createWorkbook(file, wbSettings);

//Excel sheet name. 0 represents first sheet
WritableSheet sheet = workbook.createSheet("MyUserList", 0);

try {
sheet.addCell(new Label(0, 0, "Contact")); // column and row
sheet.addCell(new Label(1, 0, "Name"));
sheet.addCell(new Label(2, 0, "Age"));

if (cursor.moveToFirst()) {
do {
String contact = cursor.getString(cursor.getColumnIndex(DatabaseHandler.USERPHONE));
String name = cursor.getString(cursor.getColumnIndex(DatabaseHandler.USERNAME));
String age = cursor.getString(cursor.getColumnIndex(DatabaseHandler.USERAGE));

int i = cursor.getPosition() + 1;

sheet.addCell(new Label(0, i, contact));
sheet.addCell(new Label(1, i, name));
sheet.addCell(new Label(2, i, age));
} while (cursor.moveToNext());
}

//closing cursor
cursor.close();

} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}

workbook.write();

try {
workbook.close();
} catch (WriteException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}

Aucun commentaire:

Enregistrer un commentaire