Monday, 20 January 2014

Android SQLite data to CSV format

SQLite to CSV

Its easy to export your current SQLite data into Excel or CSV format.

This can be achieved by simple code, which includes csv text file format, which we need to write through code.

CSV format works on the basis of comma and new line.

The below code includes.
1. File creation
2. Writing data to file
3. Fetching data from SQLite & writing in csv format.

You can modify your format however you want, keeping in your mind about commas.

Call this method & pass your file & directory path.



private Boolean backupDatabaseCSV(String outFileName) {
    MyLog.d(TAG, "backupDatabaseCSV");
    Boolean returnCode = false;
    int i = 0;
    String csvHeader = "";
    String csvValues = "";
    for (i = 0; i < GC.CURCOND_COLUMN_NAMES.length; i++) {
        if (csvHeader.length() > 0) {
            csvHeader += ",";
        }
        csvHeader += "\"" + GC.CURCOND_COLUMN_NAMES[i] + "\"";
    }

    csvHeader += "\n";
    MyLog.d(TAG, "header=" + csvHeader);
    dbAdapter.open();
    try {
        File outFile = new File(outFileName);
        FileWriter fileWriter = new FileWriter(outFile);
        BufferedWriter out = new BufferedWriter(fileWriter);
        Cursor cursor = dbAdapter.getAllRows();
        if (cursor != null) {
            out.write(csvHeader);
            while (cursor.moveToNext()) {
                csvValues = Long.toString(cursor.getLong(0)) + ",";
                csvValues += Double.toString(cursor.getDouble(1))
                        + ",";
                csvValues += Double.toString(cursor.getDouble(2))
                        + ",";
                csvValues += "\"" + cursor.getString(3) + "\",";
                csvValues += Double.toString(cursor.getDouble(4))
                        + ",";
                csvValues += Double.toString(cursor.getDouble(5))
                        + ",";
                csvValues += "\"" + cursor.getString(6) + "\",";
                csvValues += Double.toString(cursor.getDouble(7))
                        + ",";
                csvValues += Double.toString(cursor.getDouble(8))
                        + ",";
                csvValues += Double.toString(cursor.getDouble(9))
                        + "\n";
                out.write(csvValues);
            }
            cursor.close();
        }
        out.close();
        returnCode = true;
    } catch (IOException e) {
        returnCode = false;
        MyLog.d(TAG, "IOException: " + e.getMessage());
    }
    dbAdapter.close();
    return returnCode;
}

Enjoy converting SQLite to CSV.

No comments:

Post a Comment