SQLite Database

Introduction

In this article, we will learn how to export Android SQLite Database to Excel or Import Excel into SQLite Database. We can use the SQLiteToExcel library to perform these functionalities.

SQLiteToExcel

It is a Lightweight Library to Convert SQLite Database to Excel and Convert Excel to SQLite and it is open-sourced in GitHub. You can find the Library in GitHub. It is small in size and its size around “16kb” only. This library is powered by “apache - poi”.
I have divided this Implementation into 4 steps as shown in the following.
Step 1
Creating a New Project with Android Studio.
Step 2
Setting up the library and AndroidManifest for the project.
Step 3
Creating a SQLite Database
Step 4
Exporting SQLite Database to Excel.
Step 5
Importing Excel into SQLite.
Without any more introduction, we will jump into the coding part.
Step 1 - Creating a New Project with Android Studio
  1. Open Android Studio and Select Create a new project.
  2. Name the project as you wish and select your activity template.
    SQLite Database
  1. Click the “Finish button to create a new project in Android Studio.
Step 2 - Setting up the library and AndroidManifest for the project
  1. Open your app level build.gradle file and add the SQLiteToExcel library using the following line.
    compile 'com.ajts.androidmads.SQLite2Excel:library:1.0.2'
  1. Then click Sync Nowto add the library.
  2. Now open your Manifest File (AndroidManifest.xml) and the following permission.
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Step 3 - Creating a SQLite Database
  1. We are aware of the usage of SQLite in Android. If you want to know how to implement SQLite operations, click here.
  2. The given codes in the link show how to create the implementation of SQLite in Android with SQLiteOpenHelper and how to perform the DB operations with SQLite. Above code will generate SQLite Database and tables.
Step 4 - Exporting SQLite Database to Excel
  1. Open your java or any Activity you want to add the functionality and add the following lines to initialize the library. By using this, you can export the file into the default location.
    SqliteToExcel sqliteToExcel = new SqliteToExcel(this, "helloworld.db");
  1. If you want to export the file in a user preferred path, use the following.
    SqliteToExcel sqliteToExcel = new SqliteToExcel(this, "helloworld.db", directory_path);
    Here, “helloworld.db” is the name of the SQLite Database created in Android Application.
  1. In this step, we will learn how to call the library to export SQLite database like an excel file to the default location or the user-defined location. This library allows us to export a single table or a list of tables or the whole database as Excel.
SINGLE TABLE
The following lines are used to export a single table.
  1. sqliteToExcel.exportSingleTable("table1", "table1.xls", new SQLiteToExcel.ExportListener() {
  2. @Override
  3. public void onStart() {
  4. }
  5. @Override
  6. public void onCompleted(String filePath) {
  7. }
  8. @Override
  9. public void onError(Exception e) {
  10. }
  11. });
LIST OF TABLES
The following lines are used to export a list of tables.
  1. sqliteToExcel.exportSingleTable(table1List, "table1.xls", new SQLiteToExcel.ExportListener() {
  2. @Override
  3. public void onStart() {
  4. }
  5. @Override
  6. public void onCompleted(String filePath) {
  7. }
  8. @Override
  9. public void onError(Exception e) {
  10. }
  11. });
WHOLE DATABASE
The following lines are used to export a list of tables.
  1. sqliteToExcel. exportAllTables ("table1.xls", new SQLiteToExcel.ExportListener() {
  2. @Override
  3. public void onStart() {
  4. }
  5. @Override
  6. public void onCompleted(String filePath) {
  7. }
  8. @Override
  9. public void onError(Exception e) {
  10. }
  11. });
Step 5 - Importing Excel into SQLite Database
In this step, we will learn how to call the library to import excel file into SQLite database.
  1. The following lines are used to initialize the library for Excel to Database conversion.
    ExcelToSQLite excelToSQLite = new ExcelToSQLite(getApplicationContext(), "helloworld.db");
  1. If you want to import a table with dropping existing table in your DB use the following.
    ExcelToSQLite excelToSQLite = new ExcelToSQLite(getApplicationContext(), "helloworld.db", true);
    Here, helloworld.db is the name of the SQLite Database created in Android Application.
  1. We can import the excel files from the Assets folder or from Directory Path with file name and extensions.
IMPORT FROM ASSETS
Use the following to import excel from assets folder of the application.
  1. excelToSQLite.importFromAsset("assetFileName.xls", new ExcelToSQLite.ImportListener() {
  2. @Override
  3. public void onStart() {
  4. }
  5. @Override
  6. public void onCompleted(String dbName) {
  7. }
  8. @Override
  9. public void onError(Exception e) {
  10. }
  11. });
IMPORT FROM DIRECTORY
Use the following lines are used to import excel files from user defined or chosen path.
  1. excelToSQLite.importFromFile(directory_path, new ExcelToSQLite.ImportListener() {
  2. @Override
  3. public void onStart() {
  4. }
  5. @Override
  6. public void onCompleted(String dbName) {
  7. }
  8. @Override
  9. public void onError(Exception e) {
  10. }
  11. });
Full Code of the Application
Full code of SQLite2ExcelActivity.java
  1. package com.ajts.androidmads.sqlite2xlDemo;
  2. import android.os.Bundle;
  3. import android.os.Environment;
  4. import android.support.v7.app.AppCompatActivity;
  5. import android.view.MenuItem;
  6. import android.view.View;
  7. import android.widget.Button;
  8. import android.widget.EditText;
  9. import android.widget.ListView;
  10. import com.ajts.androidmads.library.SQLiteToExcel;
  11. import com.ajts.androidmads.sqlite2xlDemo.adapter.CustomAdapter;
  12. import com.ajts.androidmads.sqlite2xlDemo.db.DBHelper;
  13. import com.ajts.androidmads.sqlite2xlDemo.db.DBQueries;
  14. import com.ajts.androidmads.sqlite2xlDemo.model.Users;
  15. import com.ajts.androidmads.sqlite2xlDemo.util.Utils;
  16. import java.io.File;
  17. import java.util.ArrayList;
  18. import java.util.List;
  19. public class SQLite2ExcelActivity extends AppCompatActivity {
  20. EditText edtUser, edtContactNo;
  21. Button btnSaveUser, btnExport;
  22. ListView lvUsers;
  23. CustomAdapter lvUserAdapter;
  24. List<Users> usersList = new ArrayList<>();
  25. DBHelper dbHelper;
  26. DBQueries dbQueries;
  27. @Override
  28. protected void onCreate(Bundle savedInstanceState) {
  29. super.onCreate(savedInstanceState);
  30. setContentView(R.layout.activity_sqlite_2_xl);
  31. assert getSupportActionBar() != null;
  32. getSupportActionBar().setDisplayHomeAsUpEnabled(true);
  33. dbHelper = new DBHelper(getApplicationContext());
  34. dbQueries = new DBQueries(getApplicationContext());
  35. edtUser = (EditText) findViewById(R.id.edt_user);
  36. edtContactNo = (EditText) findViewById(R.id.edt_c_no);
  37. btnSaveUser = (Button) findViewById(R.id.btn_save_user);
  38. btnExport = (Button) findViewById(R.id.btn_export);
  39. lvUsers = (ListView) findViewById(R.id.lv_users);
  40. dbQueries.open();
  41. usersList = dbQueries.readUsers();
  42. lvUserAdapter = new CustomAdapter(getApplicationContext(), usersList);
  43. lvUsers.setAdapter(lvUserAdapter);
  44. dbQueries.close();
  45. btnSaveUser.setOnClickListener(new View.OnClickListener() {
  46. @Override
  47. public void onClick(View view) {
  48. if (validate(edtUser) && validate(edtContactNo)) {
  49. dbQueries.open();
  50. Users users = new Users(edtUser.getText().toString(), edtContactNo.getText().toString());
  51. dbQueries.insertUser(users);
  52. usersList = dbQueries.readUsers();
  53. lvUserAdapter = new CustomAdapter(getApplicationContext(), usersList);
  54. lvUsers.setAdapter(lvUserAdapter);
  55. dbQueries.close();
  56. Utils.showSnackBar(view, "Successfully Inserted");
  57. }
  58. }
  59. });
  60. btnExport.setOnClickListener(new View.OnClickListener() {
  61. @Override
  62. public void onClick(final View view) {
  63. String directory_path = Environment.getExternalStorageDirectory().getPath() + "/Backup/";
  64. File file = new File(directory_path);
  65. if (!file.exists()) {
  66. file.mkdirs();
  67. }
  68. // Export SQLite DB as EXCEL FILE
  69. SQLiteToExcel sqliteToExcel = new SQLiteToExcel(getApplicationContext(), DBHelper.DB_NAME, directory_path);
  70. sqliteToExcel.exportAllTables("users.xls", new SQLiteToExcel.ExportListener() {
  71. @Override
  72. public void onStart() {
  73. }
  74. @Override
  75. public void onCompleted(String filePath) {
  76. Utils.showSnackBar(view, "Successfully Exported");
  77. }
  78. @Override
  79. public void onError(Exception e) {
  80. }
  81. });
  82. }
  83. });
  84. }
  85. boolean validate(EditText editText) {
  86. if (editText.getText().toString().length() == 0) {
  87. editText.setError("Field Required");
  88. editText.requestFocus();
  89. }
  90. return editText.getText().toString().length() > 0;
  91. }
  92. @Override
  93. public boolean onOptionsItemSelected(MenuItem item) {
  94. if (item.getItemId() == android.R.id.home)
  95. onBackPressed();
  96. return true;
  97. }
  98. }
Full code of Excel2SQLiteActivity.java
  1. package com.ajts.androidmads.sqlite2xlDemo;
  2. import android.os.Bundle;
  3. import android.os.Environment;
  4. import android.support.v7.app.AppCompatActivity;
  5. import android.view.MenuItem;
  6. import android.view.View;
  7. import android.widget.Button;
  8. import android.widget.EditText;
  9. import com.ajts.androidmads.library.ExcelToSQLite;
  10. import com.ajts.androidmads.sqlite2xlDemo.db.DBHelper;
  11. import com.ajts.androidmads.sqlite2xlDemo.db.DBQueries;
  12. import com.ajts.androidmads.sqlite2xlDemo.util.Utils;
  13. import java.io.File;
  14. public class Excel2SQLiteActivity extends AppCompatActivity {
  15. EditText edtFilePath;
  16. Button btnImport;
  17. DBHelper dbHelper;
  18. DBQueries dbQueries;
  19. String directory_path = Environment.getExternalStorageDirectory().getPath() + "/Backup/users.xls";
  20. @Override
  21. protected void onCreate(Bundle savedInstanceState) {
  22. super.onCreate(savedInstanceState);
  23. setContentView(R.layout.activity_xl_2_sqlite);
  24. dbHelper = new DBHelper(getApplicationContext());
  25. dbQueries = new DBQueries(getApplicationContext());
  26. assert getSupportActionBar() != null;
  27. getSupportActionBar().setDisplayHomeAsUpEnabled(true);
  28. edtFilePath = (EditText) findViewById(R.id.edt_file_path);
  29. btnImport = (Button) findViewById(R.id.btn_import);
  30. edtFilePath.setText(directory_path);
  31. btnImport.setOnClickListener(new View.OnClickListener() {
  32. @Override
  33. public void onClick(final View view) {
  34. File file = new File(directory_path);
  35. if (!file.exists()) {
  36. Utils.showSnackBar(view, "No file");
  37. return;
  38. }
  39. dbQueries.open();
  40. // Is used to import data from excel without dropping table
  41. // ExcelToSQLite excelToSQLite = new ExcelToSQLite(getApplicationContext(), DBHelper.DB_NAME);
  42. // if you want to add column in excel and import into DB, you must drop the table
  43. ExcelToSQLite excelToSQLite = new ExcelToSQLite(getApplicationContext(), DBHelper.DB_NAME, false);
  44. // Import EXCEL FILE to SQLite
  45. excelToSQLite.importFromFile(directory_path, new ExcelToSQLite.ImportListener() {
  46. @Override
  47. public void onStart() {
  48. }
  49. @Override
  50. public void onCompleted(String dbName) {
  51. Utils.showSnackBar(view, "Excel imported into " + dbName);
  52. }
  53. @Override
  54. public void onError(Exception e) {
  55. Utils.showSnackBar(view, "Error : " + e.getMessage());
  56. }
  57. });
  58. dbQueries.close();
  59. }
  60. });
  61. }
  62. @Override
  63. public boolean onOptionsItemSelected(MenuItem item) {
  64. if (item.getItemId() == android.R.id.home)
  65. onBackPressed();
  66. return true;
  67. }
  68. }
Note
Download Code
You can find the library in GitHub. If you like this library, do star the library in GitHub and share this library. The sample implementation of this library can be found here.