Android SQLite数据库导出/导入Excel
前言
最近在做一款记账软件,需要备份和导入的功能,所以想到了用Excel表来存储。
框架
使用方法
这是一个轻量化库用来转换SQLite数据库为Excel和转换Excel中的SQLite。
添加依赖
implementation 'com.ajts.androidmads.SQLite2Excel:library:1.0.4'
声明权限
读写外置存取权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
导出数据库到Excel
声明实例
导出到默认位置-外置存储根目录
SQLiteToExcel sqliteToExcel = new SQLiteToExcel(this, "helloworld.db");
导出到指定位置
SQLiteToExcel sqliteToExcel = new SQLiteToExcel(this, "helloworld.db", directory_path);
配置导出内容
排除数据表中的某些列不进行数据导出
ArrayList<String> columnsToExclude = new ArrayList<String>();
columnsToExclude.add("income_id");
sqliteToExcel.setExcludeColumns(columnsToExclude);
修改导出列的列名
HashMap<String, String> prettyNameMapping = new HashMap<String, String>();
prettyNameMapping.put("income_date", "Date");
sqliteToExcel.setPrettyNameMapping(prettyNameMapping);
转换导出的值
sqliteToExcel.setCustomFormatter(new SQLiteToExcel.ExportCustomFormatter() {
@Override
public String process(String columnName, String value) {
switch(columnName) {
case "income_type_id":
int v = Integer.parseInt(value);
switch(v) {
case 10:
value = "Sale";
break;
...
default:
value = "Unknown";
break;
}
break;
}
return value;
}
});
导出监听
导出指定数据库中的单个数据表
sqliteToExcel.exportSingleTable("table1", "table1.xls", new SQLiteToExcel.ExportListener() {
@Override
public void onStart() {
}
@Override
public void onCompleted(String filePath) {
}
@Override
public void onError(Exception e) {
}
});
导出指定数据库中的多个数据表
sqliteToExcel.exportSpecificTables(tablesList, "table1.xls", new SQLiteToExcel.ExportListener() {
@Override
public void onStart() {
}
@Override
public void onCompleted(String filePath) {
}
@Override
public void onError(Exception e) {
}
});
导出指定数据库中的全部数据表
sqliteToExcel.exportAllTables("table1.xls", new SQLiteToExcel.ExportListener() {
@Override
public void onStart() {
}
@Override
public void onCompleted(String filePath) {
}
@Override
public void onError(Exception e) {
}
});
导入Excel到数据库
声明实例
初始化
ExcelToSQLite excelToSQLite = new ExcelToSQLite(getApplicationContext(), "helloworld.db");
如果你要先删除表,再导入Excel,使用以下声明方法
ExcelToSQLite excelToSQLite = new ExcelToSQLite(getApplicationContext(), "helloworld.db", true);
导入监听
从Assets资源中导入
excelToSQLite.importFromAsset("assetFileName.xls", new ExcelToSQLite.ImportListener() {
@Override
public void onStart() {
}
@Override
public void onCompleted(String dbName) {
}
@Override
public void onError(Exception e) {
}
});
从文件夹中导入-填入绝对路径
excelToSQLite.importFromFile(directory_path, new ExcelToSQLite.ImportListener() {
@Override
public void onStart() {
}
@Override
public void onCompleted(String dbName) {
}
@Override
public void onError(Exception e) {
}
});
混淆
-dontwarn org.apache.poi.**