Extract data from Sqlite and store in a CSV file

im trying to return the data from the database and save it in a file as a CSV in the SDcard and attach the file and send it by email, all this works fine, and the data should be like this in Excel.

Example

COLUMN A ........... COLUMN B

123123232 .......... John

964803400 .......... Smith

657484738 .......... Mike

my problem is that when I open Excel, the data is displayed as follows

COLUMN A ........... COLUMN B

123123232 ..........

964803400 ..........

657484738 ..........

John

Smith

Mike

Here is the code Names.Java

dbUser.open(); File root=null; try { // check for SDcard root = Environment.getExternalStorageDirectory(); Log.i(TAG,"path.." +root.getAbsolutePath()); //check sdcard permission if (root.canWrite()){ File fileDir = new File(root.getAbsolutePath()+"/fun/"); fileDir.mkdirs(); Log.d("PATH",fileDir.toString()); File file= new File(fileDir, "itisfun.csv"); FileWriter filewriter = new FileWriter(file); BufferedWriter out = new BufferedWriter(filewriter); String[] div = dbUser.getVname_Mnumber(sharedUsername1,product).toString().split(","); Log.d(sharedUsername1, product); Log.d("VVVVVVVVVV", dbUser.getVname_Mnumber(sharedUsername1,product).toString()); for (int i =0; i<div.length;i++) out.write( div[i] +"\n" ); out.close(); } } catch (IOException e) { Log.e("ERROR:---", "Could not write file to SDCard" + e.getMessage()); } 

Here is my DBadapter

 public String getVname_Mnumber(String date , String Vname) throws SQLException { String[] whereArgs = new String[]{date,Vname}; Cursor mcursor = db.rawQuery("SELECT MeterNumber,VendorName FROM " + SCAN_TABLE + " WHERE Date = ? AND VendorName = ? ",whereArgs); ArrayList<String> results = new ArrayList<String>(); ArrayList<String> results1 = new ArrayList<String>(); while (mcursor.moveToNext()) { results.add(mcursor.getString(0)); results1.add(mcursor.getString(1)); } return results + ","+ results1; } 

appreciate your help

+4
source share
1 answer

You basically create two ArrayLists: the first contains only column 0 from the cursor, and the second contains only column 1. Then you return all the results of column 0, followed by ",", followed by all the results for column 1.

Try StringBuilder for everything. Example...

 StringBuilder sb = new StringBuilder(); while (mcursor.moveToNext()) { sb.append(mcursor.getString(0) + "," + mcursor.getString(1) + "\n"); } return sb.toString(); 
+3
source

All Articles