├── app-kt
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── values
│ │ │ │ ├── strings.xml
│ │ │ │ ├── colors.xml
│ │ │ │ └── styles.xml
│ │ │ ├── mipmap-hdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-mdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-anydpi-v26
│ │ │ │ ├── ic_launcher.xml
│ │ │ │ └── ic_launcher_round.xml
│ │ │ ├── layout
│ │ │ │ └── activity_main.xml
│ │ │ ├── drawable-v24
│ │ │ │ └── ic_launcher_foreground.xml
│ │ │ └── drawable
│ │ │ │ └── ic_launcher_background.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ │ └── com
│ │ │ └── liyu
│ │ │ └── demokt
│ │ │ └── MainActivity.kt
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── liyu
│ │ │ └── demokt
│ │ │ └── ExampleUnitTest.kt
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── liyu
│ │ └── demokt
│ │ └── ExampleInstrumentedTest.kt
├── proguard-rules.pro
└── build.gradle
├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── assets
│ │ │ ├── user.xls
│ │ │ └── litepal.xml
│ │ ├── res
│ │ │ ├── drawable
│ │ │ │ └── yuyu.png
│ │ │ ├── values
│ │ │ │ ├── strings.xml
│ │ │ │ ├── colors.xml
│ │ │ │ ├── dimens.xml
│ │ │ │ └── styles.xml
│ │ │ ├── mipmap-hdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-mdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xhdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── values-w820dp
│ │ │ │ └── dimens.xml
│ │ │ └── layout
│ │ │ │ └── activity_main.xml
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── liyu
│ │ │ │ └── demo
│ │ │ │ ├── App.java
│ │ │ │ ├── User.java
│ │ │ │ └── MainActivity.java
│ │ └── AndroidManifest.xml
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── liyu
│ │ │ └── demo
│ │ │ └── ExampleUnitTest.java
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── liyu
│ │ └── demo
│ │ └── ExampleInstrumentedTest.java
├── proguard-rules.pro
└── build.gradle
├── sqlitetoexcel-kt
├── .gitignore
├── consumer-rules.pro
├── src
│ ├── main
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ │ └── com
│ │ │ └── liyu
│ │ │ └── sqlitetoexcel
│ │ │ └── kt
│ │ │ └── SQLiteToExcel.kt
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── liyu
│ │ │ └── sqlitetoexcel
│ │ │ └── kt
│ │ │ └── ExampleUnitTest.kt
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── liyu
│ │ └── sqlitetoexcel
│ │ └── kt
│ │ └── ExampleInstrumentedTest.kt
├── proguard-rules.pro
└── build.gradle
├── sqlitetoexcel
├── .gitignore
├── src
│ └── main
│ │ ├── res
│ │ └── values
│ │ │ └── strings.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ └── com
│ │ └── liyu
│ │ └── sqlitetoexcel
│ │ ├── SecurityUtil.java
│ │ ├── SQLiteToExcel.java
│ │ └── ExcelToSQLite.java
├── proguard-rules.pro
└── build.gradle
├── gradle.properties
├── settings.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── gradlew.bat
├── README-CN.md
├── README.md
├── gradlew
└── LICENSE
/app-kt/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/sqlitetoexcel-kt/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/sqlitetoexcel-kt/consumer-rules.pro:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/sqlitetoexcel/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/li-yu/SQLiteToExcel/HEAD/gradle.properties
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app-kt'
2 | include ':sqlitetoexcel-kt'
3 | include ':app', ':sqlitetoexcel'
4 |
--------------------------------------------------------------------------------
/app/src/main/assets/user.xls:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/li-yu/SQLiteToExcel/HEAD/app/src/main/assets/user.xls
--------------------------------------------------------------------------------
/app-kt/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | app-kt
3 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/yuyu.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/li-yu/SQLiteToExcel/HEAD/app/src/main/res/drawable/yuyu.png
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | SQLiteToExcel
3 |
4 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/li-yu/SQLiteToExcel/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | .idea
5 | .DS_Store
6 | /build
7 | /captures
8 | .externalNativeBuild
9 |
--------------------------------------------------------------------------------
/sqlitetoexcel/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | SQLiteToExcel
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/li-yu/SQLiteToExcel/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/li-yu/SQLiteToExcel/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/li-yu/SQLiteToExcel/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/li-yu/SQLiteToExcel/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app-kt/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/li-yu/SQLiteToExcel/HEAD/app-kt/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app-kt/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/li-yu/SQLiteToExcel/HEAD/app-kt/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app-kt/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/li-yu/SQLiteToExcel/HEAD/app-kt/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app-kt/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/li-yu/SQLiteToExcel/HEAD/app-kt/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/li-yu/SQLiteToExcel/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app-kt/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/li-yu/SQLiteToExcel/HEAD/app-kt/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app-kt/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/li-yu/SQLiteToExcel/HEAD/app-kt/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app-kt/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/li-yu/SQLiteToExcel/HEAD/app-kt/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app-kt/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/li-yu/SQLiteToExcel/HEAD/app-kt/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app-kt/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/li-yu/SQLiteToExcel/HEAD/app-kt/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app-kt/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/li-yu/SQLiteToExcel/HEAD/app-kt/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/sqlitetoexcel-kt/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 | /
5 |
--------------------------------------------------------------------------------
/app-kt/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #6200EE
4 | #3700B3
5 | #03DAC5
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Thu Jul 09 19:54:08 CST 2020
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip
7 |
--------------------------------------------------------------------------------
/app/src/main/assets/litepal.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/app-kt/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app-kt/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/sqlitetoexcel/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/main/java/com/liyu/demo/App.java:
--------------------------------------------------------------------------------
1 | package com.liyu.demo;
2 |
3 | import android.app.Application;
4 |
5 | import org.litepal.LitePal;
6 |
7 | /**
8 | * Created by liyu on 2017/3/24.
9 | */
10 |
11 | public class App extends Application {
12 | @Override
13 | public void onCreate() {
14 | super.onCreate();
15 | LitePal.initialize(this);
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/app/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/app-kt/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app-kt/src/test/java/com/liyu/demokt/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.liyu.demokt
2 |
3 | import org.junit.Test
4 |
5 | import org.junit.Assert.*
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * See [testing documentation](http://d.android.com/tools/testing).
11 | */
12 | class ExampleUnitTest {
13 | @Test
14 | fun addition_isCorrect() {
15 | assertEquals(4, 2 + 2)
16 | }
17 | }
--------------------------------------------------------------------------------
/sqlitetoexcel-kt/src/test/java/com/liyu/sqlitetoexcel/kt/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.liyu.sqlitetoexcel.kt
2 |
3 | import org.junit.Test
4 |
5 | import org.junit.Assert.*
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * See [testing documentation](http://d.android.com/tools/testing).
11 | */
12 | class ExampleUnitTest {
13 | @Test
14 | fun addition_isCorrect() {
15 | assertEquals(4, 2 + 2)
16 | }
17 | }
--------------------------------------------------------------------------------
/app/src/test/java/com/liyu/demo/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.liyu.demo;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() throws Exception {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in D:\Android\sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/sqlitetoexcel/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in D:\Android\sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/app-kt/src/androidTest/java/com/liyu/demokt/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.liyu.demokt
2 |
3 | import android.support.test.InstrumentationRegistry
4 | import android.support.test.runner.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext
22 | assertEquals("com.liyu.demokt", appContext.packageName)
23 | }
24 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/liyu/demo/User.java:
--------------------------------------------------------------------------------
1 | package com.liyu.demo;
2 |
3 | import org.litepal.crud.DataSupport;
4 |
5 | /**
6 | * Created by liyu on 2017/3/24.
7 | */
8 |
9 | public class User extends DataSupport {
10 |
11 | private String name;
12 |
13 | private float price;
14 |
15 | private byte[] cover;
16 |
17 | public byte[] getCover() {
18 | return cover;
19 | }
20 |
21 | public void setCover(byte[] cover) {
22 | this.cover = cover;
23 | }
24 |
25 | public String getName() {
26 | return name;
27 | }
28 |
29 | public void setName(String name) {
30 | this.name = name;
31 | }
32 |
33 | public float getPrice() {
34 | return price;
35 | }
36 |
37 | public void setPrice(float price) {
38 | this.price = price;
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/app-kt/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/sqlitetoexcel-kt/src/androidTest/java/com/liyu/sqlitetoexcel/kt/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.liyu.sqlitetoexcel.kt
2 |
3 | import android.support.test.InstrumentationRegistry
4 | import android.support.test.runner.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext
22 | assertEquals("com.liyu.sqlitetoexcel.kt.test", appContext.packageName)
23 | }
24 | }
--------------------------------------------------------------------------------
/sqlitetoexcel-kt/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/app-kt/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
18 |
19 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/liyu/demo/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.liyu.demo;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumentation test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() throws Exception {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("com.liyu.sqlitetoexcel", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/app-kt/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 27
5 |
6 | defaultConfig {
7 | applicationId "com.liyu.sqlitetoexcel"
8 | minSdkVersion 15
9 | targetSdkVersion 27
10 | versionCode 1
11 | versionName "1.0"
12 | }
13 | buildTypes {
14 | release {
15 | minifyEnabled false
16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
17 | }
18 | }
19 | packagingOptions {
20 | exclude 'META-INF/DEPENDENCIES'
21 | exclude 'META-INF/NOTICE'
22 | exclude 'META-INF/LICENSE'
23 | exclude 'META-INF/LICENSE.txt'
24 | exclude 'META-INF/NOTICE.txt'
25 | }
26 | }
27 |
28 | dependencies {
29 | implementation fileTree(include: ['*.jar'], dir: 'libs')
30 | implementation 'com.android.support:appcompat-v7:27.1.1'
31 | implementation 'org.litepal.android:core:1.5.1'
32 | implementation project(path: ':sqlitetoexcel')
33 | }
34 |
--------------------------------------------------------------------------------
/sqlitetoexcel-kt/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'kotlin-android'
3 | apply plugin: 'kotlin-android-extensions'
4 |
5 | android {
6 | compileSdkVersion 30
7 | buildToolsVersion "30.0.0"
8 |
9 | defaultConfig {
10 | minSdkVersion 15
11 | targetSdkVersion 30
12 | versionCode 1
13 | versionName "1.0"
14 |
15 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
16 | consumerProguardFiles "consumer-rules.pro"
17 | }
18 |
19 | buildTypes {
20 | release {
21 | minifyEnabled false
22 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
23 | }
24 | }
25 | }
26 |
27 | dependencies {
28 | implementation fileTree(dir: "libs", include: ["*.jar"])
29 | implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
30 | implementation 'com.android.support:appcompat-v7:28.0.0'
31 | testImplementation 'junit:junit:4.12'
32 | androidTestImplementation 'com.android.support.test:runner:1.0.2'
33 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
34 | implementation project(':sqlitetoexcel')
35 | }
--------------------------------------------------------------------------------
/app-kt/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 | apply plugin: 'kotlin-android'
3 | apply plugin: 'kotlin-android-extensions'
4 |
5 | android {
6 | compileSdkVersion 30
7 | buildToolsVersion "30.0.0"
8 |
9 | defaultConfig {
10 | applicationId "com.liyu.demokt"
11 | minSdkVersion 15
12 | targetSdkVersion 30
13 | versionCode 1
14 | versionName "1.0"
15 |
16 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
17 | }
18 |
19 | buildTypes {
20 | release {
21 | minifyEnabled false
22 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
23 | }
24 | }
25 | }
26 |
27 | dependencies {
28 | implementation fileTree(dir: "libs", include: ["*.jar"])
29 | implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
30 | implementation 'com.android.support:appcompat-v7:28.0.0'
31 | implementation 'com.android.support.constraint:constraint-layout:1.1.3'
32 | testImplementation 'junit:junit:4.12'
33 | androidTestImplementation 'com.android.support.test:runner:1.0.2'
34 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
35 | implementation project(path: ':sqlitetoexcel-kt')
36 | }
37 |
--------------------------------------------------------------------------------
/sqlitetoexcel/src/main/java/com/liyu/sqlitetoexcel/SecurityUtil.java:
--------------------------------------------------------------------------------
1 | package com.liyu.sqlitetoexcel;
2 |
3 | import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
4 | import org.apache.poi.hssf.usermodel.HSSFWorkbook;
5 | import org.apache.poi.poifs.filesystem.POIFSFileSystem;
6 |
7 | import java.io.BufferedInputStream;
8 | import java.io.File;
9 | import java.io.FileInputStream;
10 | import java.io.FileOutputStream;
11 |
12 | /**
13 | * Created by liyu on 2017/7/20.
14 | */
15 |
16 | public class SecurityUtil {
17 |
18 | /**
19 | * Encrypt a file, support .xls file only
20 | *
21 | * @param file
22 | * @param encryptKey
23 | * @throws Exception
24 | */
25 | public static void EncryptFile(File file, String encryptKey) throws Exception {
26 | FileInputStream fileInput = new FileInputStream(file.getPath());
27 | BufferedInputStream bufferInput = new BufferedInputStream(fileInput);
28 | POIFSFileSystem poiFileSystem = new POIFSFileSystem(bufferInput);
29 | Biff8EncryptionKey.setCurrentUserPassword(encryptKey);
30 | HSSFWorkbook workbook = new HSSFWorkbook(poiFileSystem, true);
31 | FileOutputStream fileOut = new FileOutputStream(file.getPath());
32 | workbook.writeProtectWorkbook(Biff8EncryptionKey.getCurrentUserPassword(), "");
33 | workbook.write(fileOut);
34 | bufferInput.close();
35 | fileOut.close();
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
13 |
14 |
19 |
20 |
28 |
29 |
38 |
39 |
--------------------------------------------------------------------------------
/app-kt/src/main/java/com/liyu/demokt/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.liyu.demokt
2 |
3 | import android.app.ProgressDialog
4 | import android.os.Bundle
5 | import android.os.Environment
6 | import android.support.v7.app.AppCompatActivity
7 | import android.view.View
8 | import android.widget.Toast
9 | import com.liyu.sqlitetoexcel.kt.SQLiteToExcel
10 | import java.io.File
11 |
12 | class MainActivity : AppCompatActivity() {
13 |
14 | override fun onCreate(savedInstanceState: Bundle?) {
15 | super.onCreate(savedInstanceState)
16 | setContentView(R.layout.activity_main)
17 | }
18 |
19 | fun onClick(view: View) {
20 | val progressDialog = ProgressDialog(this)
21 | progressDialog.setMessage("导出中...")
22 | val dbpath = (Environment.getExternalStorageDirectory().path
23 | + File.separator + "citys.db")
24 |
25 | SQLiteToExcel(this).start {
26 | databasePath = dbpath
27 | tables = arrayOf("citys")
28 | outputPath = Environment.getExternalStorageDirectory().path
29 | outputFileName = "2020citys.xls"
30 | encryptKey = "12345678"
31 | protectKey = "87654321"
32 | onStart {
33 | progressDialog.show()
34 | }
35 | onCompleted {
36 | progressDialog.dismiss()
37 | Toast.makeText(this@MainActivity, "导出成功!$it", Toast.LENGTH_SHORT).show()
38 | }
39 | onError {
40 | Toast.makeText(this@MainActivity, "$it", Toast.LENGTH_SHORT).show()
41 | }
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/app-kt/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/sqlitetoexcel-kt/src/main/java/com/liyu/sqlitetoexcel/kt/SQLiteToExcel.kt:
--------------------------------------------------------------------------------
1 | package com.liyu.sqlitetoexcel.kt
2 |
3 | import android.content.Context
4 | import java.lang.Exception
5 |
6 | class SQLiteToExcel(private val context: Context) {
7 |
8 | var databasePath: String? = null
9 | var tables: Array = arrayOf("")
10 | var outputPath: String? = null
11 | var outputFileName: String? = null
12 | var encryptKey: String? = null
13 | var protectKey: String? = null
14 |
15 | private var onCompleted: ((String) -> Unit)? = null
16 | private var onError: ((Throwable) -> Unit)? = null
17 | private var onStart: (() -> Unit)? = null
18 |
19 | fun start(block: SQLiteToExcel.() -> Unit): String? {
20 | block()
21 | val sqLiteToExcel = com.liyu.sqlitetoexcel.SQLiteToExcel.Builder(context)
22 | .setDataBase(databasePath)
23 | .setTables(*tables)
24 | .setOutputPath(outputPath)
25 | .setOutputFileName(outputFileName)
26 | .setEncryptKey(encryptKey)
27 | .setProtectKey(protectKey)
28 | .build()
29 | if (onCompleted == null && onError == null && onStart == null) {
30 | return sqLiteToExcel.start()
31 | } else {
32 | sqLiteToExcel.start(object : com.liyu.sqlitetoexcel.SQLiteToExcel.ExportListener {
33 | override fun onStart() {
34 | onStartInner()
35 | }
36 |
37 | override fun onCompleted(filePath: String) {
38 | onCompletedInner(filePath)
39 | }
40 |
41 | override fun onError(e: Exception) {
42 | onErrorInner(e)
43 | }
44 | })
45 | return null
46 | }
47 | }
48 |
49 | fun onCompleted(block: (String) -> Unit) {
50 | onCompleted = block
51 | }
52 |
53 | fun onError(block: (Throwable) -> Unit) {
54 | onError = block
55 | }
56 |
57 | fun onStart(block: () -> Unit) {
58 | onStart = block
59 | }
60 |
61 | private fun onCompletedInner(path: String) {
62 | onCompleted?.invoke(path)
63 | }
64 |
65 | private fun onErrorInner(exception: Throwable) {
66 | onError?.invoke(exception)
67 | }
68 |
69 | private fun onStartInner() {
70 | onStart?.invoke()
71 | }
72 | }
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/README-CN.md:
--------------------------------------------------------------------------------
1 | # SQLiteToExcel
2 |
3 | [English README](README-EN.md)
4 |
5 | SQLiteToExcel 库整合了 [Apache POI](http://poi.apache.org/) 和一些基本的数据库操作,使得 SQLite 和 Excel 之间相互转换更加便捷。
6 |
7 | 从 v1.0.5 版本开始,不再支持 **xlsx 格式**,因为 poi ooxml 库和其他一些相关的依赖太大了,体积超过了 10MB,同时开发过程中也发现 poi 对于 Android 支持不够全面,放弃 xlsx 也是挺无奈的,个人觉得 xls 格式对于我们来说已经够用。
8 |
9 | v1.0.8 版本开始支持自定义 SQL 查询导出了。
10 |
11 | ## 更新历史
12 | [Release Notes](https://github.com/li-yu/SQLiteToExcel/releases)
13 |
14 | ## 如何使用
15 | #### 1. 添加 Gradle 依赖
16 | ``` Gradle
17 | implementation 'com.liyu.tools:sqlitetoexcel:1.0.10'
18 | ```
19 |
20 | #### 2. SQLite -> Excel [demo](https://github.com/li-yu/SQLiteToExcel/blob/master/app/src/main/java/com/liyu/demo/MainActivity.java)
21 | ```java
22 | new SQLiteToExcel
23 | .Builder(this)
24 | .setDataBase(databasePath) //必须。 小提示:内部数据库可以通过 context.getDatabasePath("internal.db").getPath() 获取。
25 | .setTables(table1, table2) //可选, 如果不设置,则默认导出全部表。
26 | .setOutputPath(outoutPath) //可选, 如果不设置,默认输出路径为 app ExternalFilesDir。
27 | .setOutputFileName("test.xls") //可选, 如果不设置,输出的文件名为 xxx.db.xls。
28 | .setEncryptKey("1234567") //可选,可对导出的文件进行加密。
29 | .setProtectKey("9876543") //可选,可对导出的表格进行只读的保护。
30 | .start(ExportListener); // 或者使用 .start() 同步方法。
31 | ```
32 |
33 | 自定义 SQL 导出:
34 | ```java
35 | new SQLiteToExcel
36 | .Builder(this)
37 | .setDataBase(databasePath)
38 | .setSQL("select name as '名字', price as '价格' from user where name like '%小鱼%'")
39 | .start(ExportListener);
40 | ```
41 |
42 | #### 3. Excel -> SQLite [demo](https://github.com/li-yu/SQLiteToExcel/blob/master/app/src/main/java/com/liyu/demo/MainActivity.java)
43 | ```java
44 | new ExcelToSQLite
45 | .Builder(this)
46 | .setDataBase(databasePath) // 可选,如果不设置,默认为 “*.xls.db”,位于内部 database 目录下。
47 | .setAssetFileName("user.xls") // 如果文件在 asset 目录。
48 | .setFilePath("/storage/doc/user.xls") // 如果文件在其他目录。
49 | .setDecryptKey("1234567") // 可选,如果需要解密文档
50 | .setDateFormat("yyyy-MM-dd HH:mm:ss") // 可选,如果需要统一格式化日期单元格
51 | .start(ImportListener); // 或者使用 .start() 同步方法。
52 | ```
53 |
54 | #### 4. 感谢(如何支持 xlsx 可以参考以下仓库)
55 | - [https://github.com/centic9/poi-on-android](https://github.com/centic9/poi-on-android)
56 | - [https://github.com/FasterXML/aalto-xml](https://github.com/FasterXML/aalto-xml)
57 | - [https://github.com/johnrengelman/shadow](https://github.com/johnrengelman/shadow)
58 |
59 | #### 5. 注意事项
60 | * 读写外部文件时,Android 6.0 及以上版本需处理运行时权限。
61 | * Excel 导入 SQLite 时,默认取 excel 中 sheet 的**第一行**作为数据库表的列名,样式请参考 [demo](https://github.com/li-yu/SQLiteToExcel/blob/master/app/src/main/assets/user.xls)。
62 | * 目前仅支持 blob 字段导出为图片,因为我也不知道 byte[] 是文件还是图片。
63 | * ~~数据库文件须位于```/data/data/包名/databases/```下,一般都是位于这个目录下。~~
64 |
65 | ## 联系我
66 | * Email: [liyu2140@gmail.com](mailto:liyu2140@gmail.com)
67 | * Weibo: [@呵呵小小鱼](http://weibo.com/u/1241167880)
68 |
--------------------------------------------------------------------------------
/sqlitetoexcel/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'com.github.dcendents.android-maven'
3 | apply plugin: 'com.jfrog.bintray'
4 |
5 | android {
6 | compileSdkVersion 27
7 |
8 | defaultConfig {
9 | minSdkVersion 15
10 | targetSdkVersion 27
11 | versionCode 10
12 | versionName "1.0.10"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | }
21 |
22 | dependencies {
23 | implementation fileTree(dir: 'libs', include: ['*.jar'])
24 | api 'org.apache.poi:poi:3.16'
25 | implementation 'com.android.support:support-annotations:25.3.0'
26 | }
27 |
28 | def siteUrl = 'https://github.com/li-yu/SQLiteToExcel'
29 | def gitUrl = 'https://github.com/li-yu/SQLiteToExcel.git'
30 |
31 | version = "1.0.10"
32 | group = "com.liyu.tools"
33 |
34 | Properties properties = new Properties()
35 | properties.load(project.rootProject.file('local.properties').newDataInputStream())
36 | bintray {
37 | user = properties.getProperty("bintray.user")
38 | key = properties.getProperty("bintray.apikey")
39 | configurations = ['archives']
40 | pkg {
41 | repo = "maven"
42 | name = "SQLiteToExcel" //发布到JCenter上的项目名字
43 | websiteUrl = siteUrl
44 | vcsUrl = gitUrl
45 | licenses = ["Apache-2.0"]
46 | publish = true
47 | version {
48 | name = '1.0.10'
49 | released = new Date()
50 | vcsTag = 'v1.0.10'
51 | attributes = ['gradle-plugin': 'com.use.less:com.use.less.gradle:gradle-useless-plugin']
52 | desc = 'A simple lib for Android to export SQLite to Excel.'
53 | }
54 | }
55 | }
56 |
57 | install {
58 | repositories.mavenInstaller {
59 | // This generates POM.xml with proper parameters
60 | pom {
61 | project {
62 | packaging 'aar'
63 | // Add your description here
64 | name 'SQLiteToExcel'
65 | description 'A simple lib for Android to export SQLite to Excel.'
66 | url siteUrl
67 | // Set your license
68 | licenses {
69 | license {
70 | name 'The Apache Software License, Version 2.0'
71 | url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
72 | }
73 | }
74 | developers {
75 | developer {
76 | id 'li-yu'
77 | name 'liyu'
78 | email 'me@liyuyu.cn'
79 | }
80 | }
81 | scm {
82 | connection gitUrl
83 | developerConnection gitUrl
84 | url siteUrl
85 | }
86 | }
87 | }
88 | }
89 | }
90 | task sourcesJar(type: Jar) {
91 | from android.sourceSets.main.java.srcDirs
92 | classifier = 'sources'
93 | }
94 | task javadoc(type: Javadoc) {
95 | source = android.sourceSets.main.java.srcDirs
96 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
97 | }
98 | task javadocJar(type: Jar, dependsOn: javadoc) {
99 | from javadoc.destinationDir
100 | classifier = 'javadoc'
101 | }
102 | artifacts {
103 | archives javadocJar
104 | archives sourcesJar
105 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # SQLiteToExcel
2 |
3 | [ ](https://bintray.com/li-yu/maven/SQLiteToExcel/_latestVersion)
4 |
5 | [中文版 README](README-CN.md)
6 |
7 | The SQLiteToExcel library integrates [Apache POI](http://poi.apache.org/) and some basic database query operations, making it easier to convert between SQLite and Excel.
8 |
9 | From v1.0.5, **not support xlsx** format any more, because poi ooxml lib and other dependencies are so big( > 10 MB), and there are some strange problems on Android.
10 |
11 | From v1.0.8, support custom SQL query.
12 |
13 | ## Version history
14 | [Release Notes](https://github.com/li-yu/SQLiteToExcel/releases)
15 |
16 | ## How to use
17 | #### 1. Add Gradle dependencies
18 | ``` Gradle
19 | compile 'com.liyu.tools:sqlitetoexcel:1.0.10'
20 | ```
21 |
22 | #### 2. SQLite -> Excel [demo](https://github.com/li-yu/SQLiteToExcel/blob/master/app/src/main/java/com/liyu/demo/MainActivity.java)
23 | ```java
24 | new SQLiteToExcel
25 | .Builder(this)
26 | .setDataBase(databasePath) //Required. Tips: internal database path can be got by context.getDatabasePath("internal.db").getPath()
27 | .setTables(table1, table2) //Optional, if null, all tables will be export.
28 | .setOutputPath(outoutPath) //Optional, if null, default output path is app ExternalFilesDir.
29 | .setOutputFileName("test.xls") //Optional, if null, default output file name is xxx.db.xls
30 | .setEncryptKey("1234567") //Optional, if you want to encrypt the output file.
31 | .setProtectKey("9876543") //Optional, if you want to set the sheet read only.
32 | .start(ExportListener); // or .start() for synchronous method.
33 | ```
34 |
35 | Custom SQL:
36 | ```java
37 | new SQLiteToExcel
38 | .Builder(this)
39 | .setDataBase(databasePath)
40 | .setSQL("select name as USER_NAME, price as USER_PRICE from user where name like '%FRANK%'")
41 | .start(ExportListener);
42 | ```
43 |
44 | #### 3. Excel -> SQLite [demo](https://github.com/li-yu/SQLiteToExcel/blob/master/app/src/main/java/com/liyu/demo/MainActivity.java)
45 | ```java
46 | new ExcelToSQLite
47 | .Builder(this)
48 | .setDataBase(databasePath) // Optional, default is "*.xls.db" in internal database path.
49 | .setAssetFileName("user.xls") // if it is a asset file.
50 | .setFilePath("/storage/doc/user.xls") // if it is a normal file.
51 | .setDecryptKey("1234567") // Optional, if need to decrypt the file.
52 | .setDateFormat("yyyy-MM-dd HH:mm:ss") // Optional, if need to format date cell.
53 | .start(ImportListener); // or .start() for synchronous method.
54 | ```
55 |
56 | #### 4. Thanks (how to support xlsx?)
57 | - [https://github.com/centic9/poi-on-android](https://github.com/centic9/poi-on-android)
58 | - [https://github.com/FasterXML/aalto-xml](https://github.com/FasterXML/aalto-xml)
59 | - [https://github.com/johnrengelman/shadow](https://github.com/johnrengelman/shadow)
60 |
61 | #### 5. Precautions
62 | * When read or write external file, Android 6.0 and above need to deal with run-time permissions.
63 | * When convert Excel to SQLite, take excel sheet first row as the database table column name, please refer to the style [demo](https://github.com/li-yu/SQLiteToExcel/blob/master/app/src/main/assets/user.xls).
64 | * Currently only blob field is supported as a picture, because I do not know whether byte [] is a file or a picture.
65 | * ~~The database files must be located under ```/data/data/package name/databases/` ``, and are usually located in this directory.~~
66 |
67 | ## About me
68 | * Email: [liyu2140@gmail.com](mailto:liyu2140@gmail.com)
69 | * Weibo: [@呵呵小小鱼](http://weibo.com/u/1241167880)
70 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/app/src/main/java/com/liyu/demo/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.liyu.demo;
2 |
3 | import android.content.res.Resources;
4 | import android.database.Cursor;
5 | import android.database.sqlite.SQLiteDatabase;
6 | import android.graphics.Bitmap;
7 | import android.graphics.BitmapFactory;
8 | import android.os.Environment;
9 | import android.support.annotation.DrawableRes;
10 | import android.support.v7.app.AppCompatActivity;
11 | import android.os.Bundle;
12 | import android.view.View;
13 | import android.widget.TextView;
14 |
15 | import com.liyu.sqlitetoexcel.ExcelToSQLite;
16 | import com.liyu.sqlitetoexcel.SQLiteToExcel;
17 |
18 | import java.io.ByteArrayOutputStream;
19 | import java.io.File;
20 | import java.text.SimpleDateFormat;
21 | import java.util.Date;
22 |
23 | public class MainActivity extends AppCompatActivity {
24 |
25 | private TextView tv;
26 |
27 | private String outputFile;
28 |
29 | @Override
30 | protected void onCreate(Bundle savedInstanceState) {
31 | super.onCreate(savedInstanceState);
32 | setContentView(R.layout.activity_main);
33 |
34 | tv = findViewById(R.id.tv);
35 |
36 | User user = new User();
37 | user.setName("呵呵小鱼");
38 | user.setPrice(19.89f);
39 | user.setCover(getResByte(R.drawable.yuyu));
40 | user.save();
41 |
42 | }
43 |
44 | public void onExport(View v) {
45 |
46 | String databasePath1 = this.getDatabasePath("ste_db.db").getAbsolutePath();
47 |
48 | String databasePath2 = Environment.getExternalStorageDirectory().getPath()
49 | + File.separator + "citychina.db";
50 |
51 | new SQLiteToExcel
52 | .Builder(this)
53 | .setDataBase(databasePath1)
54 | // .setTables("user")
55 | // .setPath(Environment.getExternalStorageDirectory().getPath())
56 | // .setFileName("test.xls")
57 | .setSQL("select name as '名字', price as '价格' from user where name like '%小鱼%'")
58 | .setEncryptKey("1234567")
59 | .setProtectKey("9876543")
60 | .start(new SQLiteToExcel.ExportListener() {
61 | @Override
62 | public void onStart() {
63 | tv.append(makeLog("\n" +
64 | "Export importTables--->"));
65 | }
66 |
67 | @Override
68 | public void onCompleted(String filePath) {
69 | tv.append(makeLog("\n" +
70 | "Export completed--->" + filePath));
71 | outputFile = filePath;
72 | }
73 |
74 | @Override
75 | public void onError(Exception e) {
76 | tv.append(makeLog("\n" +
77 | "Export error--->" + e.toString()));
78 |
79 | }
80 | });
81 | }
82 |
83 | public void onImport(View v) {
84 |
85 | final String databasePath1 = this.getDatabasePath("internal.db").getAbsolutePath();
86 |
87 | final String databasePath2 = Environment.getExternalStorageDirectory().getPath()
88 | + File.separator + "external.db";
89 |
90 | new ExcelToSQLite
91 | .Builder(this)
92 | // .setDataBase(databasePath1)
93 | .setAssetFileName("user.xls")
94 | // .setFilePath(outputFile)
95 | .setDecryptKey("1234567")
96 | .setDateFormat("yyyy-MM-dd HH:mm:ss")
97 | .start(new ExcelToSQLite.ImportListener() {
98 | @Override
99 | public void onStart() {
100 | tv.append(makeLog("\n" +
101 | "Import importTables--->"));
102 | }
103 |
104 | @Override
105 | public void onCompleted(String result) {
106 | tv.append(makeLog("\n" +
107 | "Import completed--->" + result));
108 | showDbMsg(result);
109 | }
110 |
111 | @Override
112 | public void onError(Exception e) {
113 | tv.append(makeLog("\n" +
114 | "Import error--->" + e.toString()));
115 | }
116 | });
117 | }
118 |
119 | private void showDbMsg(String dbName) {
120 | SQLiteDatabase database;
121 | try {
122 | database = SQLiteDatabase.openOrCreateDatabase(dbName, null);
123 | Cursor cursor = database.rawQuery("select name from sqlite_master where type='table' order by name", null);
124 | while (cursor.moveToNext()) {
125 | tv.append("\nNew tables is : " + cursor.getString(0) + " ");
126 | Cursor cursor2 = database.rawQuery("select * from " + cursor.getString(0), null);
127 | while (cursor2.moveToNext()) {
128 | tv.append("\n");
129 | for (int i = 0; i < cursor2.getColumnCount(); i++) {
130 | tv.append(cursor2.getString(i) + " ");
131 | }
132 | }
133 | cursor2.close();
134 | }
135 | cursor.close();
136 | database.close();
137 | } catch (Exception e) {
138 | e.printStackTrace();
139 | }
140 | }
141 |
142 | private String makeLog(String log) {
143 | SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
144 | Date now = new Date();
145 | return log + " " + sdf.format(now);
146 | }
147 |
148 | private byte[] getResByte(@DrawableRes int id) {
149 | Resources res = getResources();
150 | Bitmap bmp = BitmapFactory.decodeResource(res, id);
151 | ByteArrayOutputStream baos = new ByteArrayOutputStream();
152 | bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
153 | return baos.toByteArray();
154 | }
155 | }
156 |
--------------------------------------------------------------------------------
/app-kt/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
203 |
--------------------------------------------------------------------------------
/sqlitetoexcel/src/main/java/com/liyu/sqlitetoexcel/SQLiteToExcel.java:
--------------------------------------------------------------------------------
1 | package com.liyu.sqlitetoexcel;
2 |
3 | import java.io.File;
4 | import java.io.FileOutputStream;
5 | import java.util.ArrayList;
6 | import java.util.Arrays;
7 | import java.util.List;
8 |
9 | import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
10 | import org.apache.poi.hssf.usermodel.HSSFRichTextString;
11 | import org.apache.poi.hssf.usermodel.HSSFWorkbook;
12 | import org.apache.poi.ss.usermodel.Cell;
13 | import org.apache.poi.ss.usermodel.ClientAnchor;
14 | import org.apache.poi.ss.usermodel.Drawing;
15 | import org.apache.poi.ss.usermodel.Row;
16 | import org.apache.poi.ss.usermodel.Sheet;
17 | import org.apache.poi.ss.usermodel.Workbook;
18 |
19 | import android.content.Context;
20 | import android.database.Cursor;
21 | import android.database.sqlite.SQLiteDatabase;
22 | import android.os.Handler;
23 | import android.os.Looper;
24 | import android.support.annotation.NonNull;
25 | import android.text.TextUtils;
26 |
27 | /**
28 | * SQLite to Excel
29 | * Created by liyu on 2015-9-8
30 | */
31 | public class SQLiteToExcel {
32 |
33 | private static Handler handler = new Handler(Looper.getMainLooper());
34 |
35 | private String protectKey;
36 | private String encryptKey;
37 | private String fileName;
38 | private String filePath;
39 | private List tables;
40 | private String sql;
41 | private String sheetName;
42 |
43 | private SQLiteDatabase database;
44 | private Workbook workbook;
45 |
46 | public static class Builder {
47 | private String dataBaseName;
48 | private String filePath;
49 | private String fileName;
50 | private String protectKey;
51 | private String encryptKey;
52 | private List tables;
53 | private String sql;
54 | private String sheetName;
55 | private Context context;
56 |
57 | public Builder(Context context) {
58 | this.context = context;
59 | }
60 |
61 | public SQLiteToExcel build() {
62 | if (TextUtils.isEmpty(dataBaseName)) {
63 | throw new IllegalArgumentException("Database name must not be null.");
64 | }
65 | if (TextUtils.isEmpty(filePath)) {
66 | this.filePath = context.getExternalFilesDir(null).getPath();
67 | }
68 | if (TextUtils.isEmpty(fileName)) {
69 | this.fileName = new File(dataBaseName).getName() + ".xls";
70 | }
71 | return new SQLiteToExcel(tables, protectKey, encryptKey, fileName, dataBaseName, filePath, sql, sheetName);
72 | }
73 |
74 | public Builder setDataBase(String dataBaseName) {
75 | this.dataBaseName = dataBaseName;
76 | return this;
77 | }
78 |
79 | /**
80 | * @param fileName
81 | * @return Builder
82 | * @deprecated Use {@link #setOutputFileName(String fileName)} instead.
83 | */
84 | @Deprecated
85 | public Builder setFileName(String fileName) {
86 | return setOutputFileName(fileName);
87 | }
88 |
89 | public Builder setOutputFileName(String fileName) {
90 | this.fileName = fileName;
91 | return this;
92 | }
93 |
94 | public Builder setProtectKey(String protectPassword) {
95 | this.protectKey = protectPassword;
96 | return this;
97 | }
98 |
99 | public Builder setEncryptKey(String encryptKey) {
100 | this.encryptKey = encryptKey;
101 | return this;
102 | }
103 |
104 | public Builder setTables(String... tables) {
105 | this.tables = Arrays.asList(tables);
106 | return this;
107 | }
108 |
109 | /**
110 | * @param path
111 | * @return Builder
112 | * @deprecated Use {@link #setOutputPath(String path)} instead.
113 | */
114 | @Deprecated
115 | public Builder setPath(String path) {
116 | return setOutputPath(path);
117 | }
118 |
119 | public Builder setOutputPath(String path) {
120 | this.filePath = path;
121 | return this;
122 | }
123 |
124 | public Builder setSQL(@NonNull String sheetName, @NonNull String sql) {
125 | this.sql = sql;
126 | this.sheetName = sheetName;
127 | return this;
128 | }
129 |
130 | public Builder setSQL(@NonNull String sql) {
131 | return setSQL("Sheet1", sql);
132 | }
133 |
134 | public String start() throws Exception {
135 | final SQLiteToExcel sqliteToExcel = build();
136 | return sqliteToExcel.start();
137 | }
138 |
139 | public void start(ExportListener listener) {
140 | final SQLiteToExcel sqliteToExcel = build();
141 | sqliteToExcel.start(listener);
142 | }
143 | }
144 |
145 | /**
146 | * import Tables task
147 | *
148 | * @return output file path
149 | */
150 | public String start() throws Exception {
151 | try {
152 | if (tables == null || tables.size() == 0) {
153 | tables = getTablesName(database);
154 | }
155 | return exportTables(tables, fileName);
156 | } catch (Exception e) {
157 | if (database != null && database.isOpen()) {
158 | database.close();
159 | }
160 | throw e;
161 | }
162 | }
163 |
164 | /**
165 | * importTables task with a listener
166 | *
167 | * @param listener callback
168 | */
169 | public void start(final ExportListener listener) {
170 | if (listener != null) {
171 | listener.onStart();
172 | }
173 | new Thread(new Runnable() {
174 |
175 | @Override
176 | public void run() {
177 | try {
178 | if (tables == null || tables.size() == 0) {
179 | tables = getTablesName(database);
180 | }
181 | final String finalFilePath = exportTables(tables, fileName);
182 | if (listener != null) {
183 | handler.post(new Runnable() {
184 | @Override
185 | public void run() {
186 | listener.onCompleted(finalFilePath);
187 | }
188 | });
189 | }
190 | } catch (final Exception e) {
191 | if (database != null && database.isOpen()) {
192 | database.close();
193 | }
194 | if (listener != null)
195 | handler.post(new Runnable() {
196 | @Override
197 | public void run() {
198 | listener.onError(e);
199 | }
200 | });
201 | }
202 | }
203 | }).start();
204 | }
205 |
206 | private SQLiteToExcel(List tables, String protectKey, String encryptKey, String fileName,
207 | String dataBaseName, String filePath, String sql, String sheetName) {
208 | this.protectKey = protectKey;
209 | this.encryptKey = encryptKey;
210 | this.fileName = fileName;
211 | this.filePath = filePath;
212 | this.sql = sql;
213 | this.sheetName = sheetName;
214 | this.tables = tables;
215 | try {
216 | database = SQLiteDatabase.openOrCreateDatabase(dataBaseName, null);
217 | } catch (Exception e) {
218 | throw new RuntimeException(e);
219 | }
220 | }
221 |
222 | /**
223 | * core code, export tables to a excel file
224 | *
225 | * @param tables database tables
226 | * @param fileName target file name
227 | * @return target file path
228 | * @throws Exception
229 | */
230 | private String exportTables(List tables, final String fileName) throws Exception {
231 | if (fileName.toLowerCase().endsWith(".xls")) {
232 | workbook = new HSSFWorkbook();
233 | } else {
234 | throw new IllegalArgumentException("File name is null or unsupported file format!");
235 | }
236 | if (TextUtils.isEmpty(sql)) {
237 | for (int i = 0; i < tables.size(); i++) {
238 | Sheet sheet = workbook.createSheet(tables.get(i));
239 | String sqlAll = "select * from " + tables.get(i);
240 | fillSheet(sqlAll, sheet);
241 | if (!TextUtils.isEmpty(protectKey)) {
242 | sheet.protectSheet(protectKey);
243 | }
244 | }
245 | } else {
246 | Sheet sheet = workbook.createSheet(sheetName);
247 | fillSheet(sql, sheet);
248 | if (!TextUtils.isEmpty(protectKey)) {
249 | sheet.protectSheet(protectKey);
250 | }
251 | }
252 | File file = new File(filePath, fileName);
253 | FileOutputStream fos1 = new FileOutputStream(file);
254 | workbook.write(fos1);
255 | if (fos1 != null) {
256 | fos1.flush();
257 | fos1.close();
258 | }
259 | workbook.close();
260 | database.close();
261 | if (!TextUtils.isEmpty(encryptKey)) {
262 | SecurityUtil.EncryptFile(file, encryptKey);
263 | }
264 |
265 | return file.getPath();
266 | }
267 |
268 | /**
269 | * Query the database ,then fill in to the sheet
270 | *
271 | * @param sql query sql
272 | * @param sheet target sheet
273 | */
274 | private void fillSheet(String sql, Sheet sheet) {
275 | Drawing patriarch = sheet.createDrawingPatriarch();
276 | Cursor cursor = database.rawQuery(sql, null);
277 | cursor.moveToFirst();
278 | final int columnsCount = cursor.getColumnCount();
279 | Row headerRow = sheet.createRow(0);
280 | for (int i = 0; i < columnsCount; i++) {
281 | Cell cellA = headerRow.createCell(i);
282 | cellA.setCellValue(new HSSFRichTextString("" + cursor.getColumnNames()[i]));
283 | }
284 | int n = 1;
285 | while (!cursor.isAfterLast()) {
286 | Row rowA = sheet.createRow(n);
287 | for (int j = 0; j < columnsCount; j++) {
288 | Cell cellA = rowA.createCell(j);
289 | if (cursor.getType(j) == Cursor.FIELD_TYPE_BLOB) {
290 | ClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, (short) j, n, (short) (j + 1), n + 1);
291 | anchor.setAnchorType(3);
292 | patriarch.createPicture(anchor, workbook.addPicture(cursor.getBlob(j), HSSFWorkbook.PICTURE_TYPE_JPEG));
293 | } else {
294 | String value = cursor.getString(j);
295 | if (!TextUtils.isEmpty(value) && value.length() >= 32767) {
296 | value = value.substring(0, 32766);
297 | }
298 | cellA.setCellValue(new HSSFRichTextString(value));
299 | }
300 | }
301 | n++;
302 | cursor.moveToNext();
303 | }
304 | cursor.close();
305 | }
306 |
307 | /**
308 | * get database all tables
309 | *
310 | * @return tables
311 | */
312 | private List getTablesName(SQLiteDatabase database) {
313 | List tables = new ArrayList<>();
314 | Cursor cursor = database.rawQuery("select name from sqlite_master where type='table' order by name", null);
315 | while (cursor.moveToNext()) {
316 | tables.add(cursor.getString(0));
317 | }
318 | cursor.close();
319 | return tables;
320 | }
321 |
322 | /**
323 | * Callbacks for export events.
324 | */
325 | public interface ExportListener {
326 | void onStart();
327 |
328 | void onCompleted(String filePath);
329 |
330 | void onError(Exception e);
331 | }
332 |
333 | }
334 |
--------------------------------------------------------------------------------
/sqlitetoexcel/src/main/java/com/liyu/sqlitetoexcel/ExcelToSQLite.java:
--------------------------------------------------------------------------------
1 | package com.liyu.sqlitetoexcel;
2 |
3 | import android.content.ContentValues;
4 | import android.content.Context;
5 | import android.database.sqlite.SQLiteDatabase;
6 | import android.os.Handler;
7 | import android.os.Looper;
8 | import android.text.TextUtils;
9 |
10 | import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
11 | import org.apache.poi.hssf.usermodel.HSSFDateUtil;
12 | import org.apache.poi.hssf.usermodel.HSSFWorkbook;
13 | import org.apache.poi.ss.usermodel.Cell;
14 | import org.apache.poi.ss.usermodel.Row;
15 | import org.apache.poi.ss.usermodel.Sheet;
16 | import org.apache.poi.ss.usermodel.Workbook;
17 |
18 | import java.io.File;
19 | import java.io.FileInputStream;
20 | import java.io.InputStream;
21 | import java.math.BigInteger;
22 | import java.text.DateFormat;
23 | import java.text.SimpleDateFormat;
24 | import java.util.ArrayList;
25 | import java.util.Iterator;
26 | import java.util.List;
27 | import java.util.regex.Pattern;
28 |
29 | /**
30 | * Excel to SQLite
31 | * Created by liyu on 2017/3/31.
32 | */
33 |
34 | public class ExcelToSQLite {
35 |
36 | private static Handler handler = new Handler(Looper.getMainLooper());
37 |
38 | private Context mContext;
39 | private String dataBaseName;
40 | private SQLiteDatabase database;
41 | private String filePath;
42 | private String assetFileName;
43 | private String decryptKey;
44 | private String dateFormat;
45 |
46 | private SimpleDateFormat sdf;
47 |
48 | public static class Builder {
49 | private Context context;
50 | private String dataBaseName;
51 | private String filePath;
52 | private String assetFileName;
53 | private String decryptKey;
54 | private String dateFormat;
55 |
56 | public Builder(Context context) {
57 | this.context = context.getApplicationContext();
58 | }
59 |
60 | public ExcelToSQLite build() {
61 | if (TextUtils.isEmpty(dataBaseName)) {
62 | throw new IllegalArgumentException("Database name must not be null.");
63 | }
64 | return new ExcelToSQLite(context, dataBaseName, filePath, assetFileName, decryptKey, dateFormat);
65 | }
66 |
67 | public Builder setDataBase(String dataBaseName) {
68 | this.dataBaseName = dataBaseName;
69 | return this;
70 | }
71 |
72 | public Builder setDateFormat(String dateFormat) {
73 | this.dateFormat = dateFormat;
74 | return this;
75 | }
76 |
77 | public Builder setFilePath(String path) {
78 | this.filePath = path;
79 | this.assetFileName = null;
80 | if (TextUtils.isEmpty(this.dataBaseName)) {
81 | this.dataBaseName = context.getDatabasePath(new File(path).getName() + ".db").getAbsolutePath();
82 | }
83 | return this;
84 | }
85 |
86 | public Builder setDecryptKey(String decryptKey) {
87 | this.decryptKey = decryptKey;
88 | return this;
89 | }
90 |
91 | public Builder setAssetFileName(String name) {
92 | this.assetFileName = name;
93 | this.filePath = null;
94 | if (TextUtils.isEmpty(this.dataBaseName)) {
95 | this.dataBaseName = context.getDatabasePath(new File(name).getName() + ".db").getPath();
96 | }
97 | return this;
98 | }
99 |
100 | public void start() {
101 | final ExcelToSQLite excelToSqlite = build();
102 | excelToSqlite.start();
103 | }
104 |
105 | public void start(ImportListener listener) {
106 | final ExcelToSQLite excelToSqlite = build();
107 | excelToSqlite.start(listener);
108 | }
109 |
110 | }
111 |
112 | private ExcelToSQLite(Context context, String dataBaseName, String filePath, String assetFileName, String decryptKey, String dateFormat) {
113 | this.mContext = context;
114 | this.filePath = filePath;
115 | this.assetFileName = assetFileName;
116 | this.decryptKey = decryptKey;
117 | this.dataBaseName = dataBaseName;
118 | this.dateFormat = dateFormat;
119 | if (!TextUtils.isEmpty(dateFormat)) {
120 | sdf = new SimpleDateFormat(dateFormat);
121 | }
122 |
123 | try {
124 | database = SQLiteDatabase.openOrCreateDatabase(dataBaseName, null);
125 | } catch (Exception e) {
126 | throw new RuntimeException(e);
127 | }
128 | }
129 |
130 | /**
131 | * start task
132 | */
133 | public boolean start() {
134 | if (TextUtils.isEmpty(filePath) && TextUtils.isEmpty(assetFileName)) {
135 | throw new IllegalArgumentException("Asset file or external file name must not be null.");
136 | }
137 | try {
138 | if (TextUtils.isEmpty(filePath)) {
139 | return importTables(mContext.getAssets().open(assetFileName), assetFileName);
140 | } else {
141 | return importTables(new FileInputStream(filePath), filePath);
142 | }
143 | } catch (Exception e) {
144 | if (database != null && database.isOpen()) {
145 | database.close();
146 | }
147 | return false;
148 | }
149 | }
150 |
151 | /**
152 | * start task with a listener
153 | *
154 | * @param listener
155 | */
156 | public void start(final ImportListener listener) {
157 | if (TextUtils.isEmpty(filePath) && TextUtils.isEmpty(assetFileName)) {
158 | throw new IllegalArgumentException("Asset file or external file name must not be null.");
159 | }
160 | if (listener != null) {
161 | listener.onStart();
162 | }
163 | new Thread(new Runnable() {
164 | @Override
165 | public void run() {
166 | try {
167 | if (TextUtils.isEmpty(filePath)) {
168 | importTables(mContext.getAssets().open(assetFileName), assetFileName);
169 | } else {
170 | importTables(new FileInputStream(filePath), filePath);
171 | }
172 | if (listener != null) {
173 | handler.post(new Runnable() {
174 | @Override
175 | public void run() {
176 | listener.onCompleted(dataBaseName);
177 | }
178 | });
179 | }
180 | } catch (final Exception e) {
181 | if (database != null && database.isOpen()) {
182 | database.close();
183 | }
184 | if (listener != null) {
185 | handler.post(new Runnable() {
186 | @Override
187 | public void run() {
188 | listener.onError(e);
189 | }
190 | });
191 | }
192 | }
193 | }
194 | }).start();
195 | }
196 |
197 | /**
198 | * core code
199 | *
200 | * @param stream asset stream or file stream
201 | * @param fileName origin file name
202 | * @throws Exception
203 | */
204 | private boolean importTables(InputStream stream, String fileName) throws Exception {
205 | Workbook workbook;
206 | if (fileName.toLowerCase().endsWith(".xls")) {
207 | if (!TextUtils.isEmpty(decryptKey)) {
208 | Biff8EncryptionKey.setCurrentUserPassword("1234567");
209 | }
210 | workbook = new HSSFWorkbook(stream);
211 | } else {
212 | throw new UnsupportedOperationException("Unsupported file format!");
213 | }
214 | stream.close();
215 | int sheetNumber = workbook.getNumberOfSheets();
216 | for (int i = 0; i < sheetNumber; i++) {
217 | createTable(workbook.getSheetAt(i));
218 | }
219 | database.close();
220 | return true;
221 | }
222 |
223 | /**
224 | * create table by sheet
225 | *
226 | * @param sheet
227 | */
228 | private void createTable(Sheet sheet) {
229 | StringBuilder createTableSql = new StringBuilder("CREATE TABLE IF NOT EXISTS ");
230 | createTableSql.append(sheet.getSheetName());
231 | createTableSql.append("(");
232 | Iterator rit = sheet.rowIterator();
233 | Row rowHeader = rit.next();
234 | List columns = new ArrayList<>();
235 | for (int i = 0; i < rowHeader.getPhysicalNumberOfCells(); i++) {
236 | createTableSql.append(rowHeader.getCell(i).getStringCellValue());
237 | if (i == rowHeader.getPhysicalNumberOfCells() - 1) {
238 | createTableSql.append(" TEXT");
239 | } else {
240 | createTableSql.append(" TEXT,");
241 | }
242 | columns.add(rowHeader.getCell(i).getStringCellValue());
243 | }
244 | createTableSql.append(")");
245 | database.execSQL(createTableSql.toString());
246 | while (rit.hasNext()) {
247 | Row row = rit.next();
248 | ContentValues values = new ContentValues();
249 | for (int n = 0; n < row.getPhysicalNumberOfCells(); n++) {
250 | if (row.getCell(n) == null) {
251 | continue;
252 | }
253 | if (row.getCell(n).getCellType() == Cell.CELL_TYPE_NUMERIC) {
254 | if (HSSFDateUtil.isCellDateFormatted(row.getCell(n))) {
255 | if (sdf == null) {
256 | values.put(columns.get(n), DateFormat.getDateTimeInstance().format(row.getCell(n).getDateCellValue()));
257 | } else {
258 | values.put(columns.get(n), sdf.format(row.getCell(n).getDateCellValue()));
259 | }
260 | } else {
261 | String value = getRealStringValueOfDouble(row.getCell(n).getNumericCellValue());
262 | values.put(columns.get(n), value);
263 | }
264 | } else if (row.getCell(n).getCellType() == Cell.CELL_TYPE_STRING) {
265 | values.put(columns.get(n), row.getCell(n).getStringCellValue());
266 | }
267 | }
268 | if (values.size() == 0)
269 | continue;
270 | long result = database.insert(sheet.getSheetName(), null, values);
271 | if (result < 0) {
272 | throw new RuntimeException("Insert value failed!");
273 | }
274 | }
275 | }
276 |
277 | private static String getRealStringValueOfDouble(Double d) {
278 | String doubleStr = d.toString();
279 | boolean b = doubleStr.contains("E");
280 | int indexOfPoint = doubleStr.indexOf('.');
281 | if (b) {
282 | int indexOfE = doubleStr.indexOf('E');
283 | BigInteger xs = new BigInteger(doubleStr.substring(indexOfPoint
284 | + BigInteger.ONE.intValue(), indexOfE));
285 | int pow = Integer.valueOf(doubleStr.substring(indexOfE
286 | + BigInteger.ONE.intValue()));
287 | int xsLen = xs.toByteArray().length;
288 | int scale = xsLen - pow > 0 ? xsLen - pow : 0;
289 | doubleStr = String.format("%." + scale + "f", d);
290 | } else {
291 | java.util.regex.Pattern p = Pattern.compile(".0$");
292 | java.util.regex.Matcher m = p.matcher(doubleStr);
293 | if (m.find()) {
294 | doubleStr = doubleStr.replace(".0", "");
295 | }
296 | }
297 | return doubleStr;
298 | }
299 |
300 | /**
301 | * Callbacks for import events.
302 | */
303 | public interface ImportListener {
304 | void onStart();
305 |
306 | void onCompleted(String dataBaseName);
307 |
308 | void onError(Exception e);
309 | }
310 |
311 | }
312 |
--------------------------------------------------------------------------------