Search code examples
databasesqliteandroid-studioandroid-layoutexport-to-excel

How to export SQLite database table to Excel file in Android Studio


So I'm creating an app which uses SQLite database on TableLayout. I want to export the Table content to to Excel sheet file. Can any please provide the library and the code to implement. Thanks in advance!


Solution

  • Try this :

    private void ExportData() {
        
             //CHECK IF YOU HAVE WRITE PERMISSIONS OR RETURN
            int permission = ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
        
            if (permission != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(getContext(), "Storage permissions not granted", Toast.LENGTH_SHORT).show();
                return;
            }
        
            //get database object
            myDbhelper = new MyDbHelper(getContext());
            SQLiteDatabase database = myDbhelper.getWritableDatabase();
        
            //delete all entries in the second table
            database.delete("Table2",null,null);
        
            //Create a cursor of the main database with your filters and sort order applied
            Cursor cursor = getActivity().getContentResolver().query(
                    uri,
                    projections,
                    selection,
                    args,
                    sortOrder);
        
            //loop through cursor and add entries from first table to second table
            try {
                while (cursor.moveToNext()) {
                    final String ColumnOneIndex = cursor.getString(cursor.getColumnIndexOrThrow("COLUMN_ONE"));
                    final String ColumnTwoIndex = cursor.getString(cursor.getColumnIndexOrThrow("COLUMN_TWO"));
                    final String ColumnThreeIndex = cursor.getString(cursor.getColumnIndexOrThrow("COLUMN_THREE"));
        
              //add entries from table one into the table two
                    ContentValues values = new ContentValues();
                    values.put("TABLE2_COLUMN_1", ColumnOneIndex);
                    values.put("TABLE2_COLUMN_2", ColumnTwoIndex );
                    values.put("TABLE2_COLUMN_3", ColumnThreeIndex);
        
                    database.insert("table2", null, values);
                }
            } finally {
                //close cursor after looping is complete
                cursor.close();
            }
        
             //create a string for where you want to save the excel file
            final String savePath = Environment.getExternalStorageDirectory() + "/excelfileTemp";
            File file = new File(savePath);
            if (!file.exists()) {
                file.mkdirs();
            }
             //create the sqLiteToExcel object
            SQLiteToExcel sqLiteToExcel = new SQLiteToExcel(getContext(), "databasefile.db",savePath);
        
            //use sqLiteToExcel object to create the excel file 
            sqLiteToExcel.exportSingleTable("table2","excelfilename.xls", new SQLiteToExcel.ExportListener() {
                @Override
                public void onStart() {
        
                }
                @Override
                public void onCompleted(String filePath) {
                    //now attach the excel file created and be directed to email activity
                    Uri newPath = Uri.parse("file://" + savePath + "/" +"excelfilename.xls");
        
                    StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
                    StrictMode.setVmPolicy(builder.build());
        
                    Intent emailintent = new Intent(Intent.ACTION_SEND);
        
                    emailintent.setType("application/vnd.ms-excel");
                    emailintent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
                    emailintent.putExtra(Intent.EXTRA_TEXT, "I'm email body.");
                    emailintent.putExtra(Intent.EXTRA_STREAM,newPath);
        
                    startActivity(Intent.createChooser(emailintent, "Send Email"));
                }
                @Override
                public void onError(Exception e) {
                    System.out.println("Error msg: " + e);
                    Toast.makeText(getContext(), "Failed to Export data", Toast.LENGTH_SHORT).show();
                }
            });
        }