Skip to content

Commit

Permalink
Support decrypt excel file
Browse files Browse the repository at this point in the history
Support format date cell
Fix "CELL_TYPE_NUMERIC" issue
  • Loading branch information
li-yu committed Jul 26, 2017
1 parent 1a2bc67 commit f1d6571
Show file tree
Hide file tree
Showing 6 changed files with 104 additions and 25 deletions.
6 changes: 4 additions & 2 deletions README-EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ From v1.0.5, **not support xlsx** format any more, because poi ooxml lib and oth
## How to use
#### 1. Add Gradle dependencies
``` Gradle
compile 'com.liyu.tools:sqlitetoexcel:1.0.5'
compile 'com.liyu.tools:sqlitetoexcel:1.0.6'
```

#### 2. SQLite -> Excel Sample code(Specific examples can be found in [demo](https://github.com/li-yu/SQLiteToExcel/blob/master/app/src/main/java/com/liyu/demo/MainActivity.java))
Expand All @@ -34,9 +34,11 @@ new SQLiteToExcel
```java
new ExcelToSQLite
.Builder(this)
.setDataBase(databasePath) //Required.
.setDataBase(databasePath) // Optional, default is "*.xls.db" in internal database path.
.setAssetFileName("user.xls") // if it is a asset file.
.setFilePath("/storage/doc/user.xls") // if it is a normal file.
.setDecryptKey("1234567") // Optional, if need to decrypt the file.
.setDateFormat("yyyy-MM-dd HH:mm:ss") // Optional, if need to format date cell.
.start(ImportListener); // or .start() for synchronous method.
```

Expand Down
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ SQLiteToExcel 库整合了 [Apache POI](http://poi.apache.org/) 和一些基本
## 如何使用
#### 1. 添加 Gradle 依赖
``` Gradle
compile 'com.liyu.tools:sqlitetoexcel:1.0.5'
compile 'com.liyu.tools:sqlitetoexcel:1.0.6'
```

#### 2. SQLite -> Excel 示例代码(具体示例可参考 [demo](https://github.com/li-yu/SQLiteToExcel/blob/master/app/src/main/java/com/liyu/demo/MainActivity.java) 工程)
Expand All @@ -34,9 +34,11 @@ new SQLiteToExcel
```java
new ExcelToSQLite
.Builder(this)
.setDataBase(databasePath) //必须
.setDataBase(databasePath) // 可选,如果不设置,默认为 “*.xls.db”,位于内部 database 目录下
.setAssetFileName("user.xls") // 如果文件在 asset 目录。
.setFilePath("/storage/doc/user.xls") // 如果文件在其他目录。
.setDecryptKey("1234567") // 可选,如果需要解密文档
.setDateFormat("yyyy-MM-dd HH:mm:ss") // 可选,如果需要统一格式化日期单元格
.start(ImportListener); // 或者使用 .start() 同步方法。
```

Expand Down
Binary file modified app/src/main/assets/user.xls
Binary file not shown.
22 changes: 13 additions & 9 deletions app/src/main/java/com/liyu/demo/MainActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ public class MainActivity extends AppCompatActivity {

private TextView tv;

private String outputFile;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Expand All @@ -48,12 +50,12 @@ public void onExport(View v) {

new SQLiteToExcel
.Builder(this)
.setDataBase(databasePath2)
.setDataBase(databasePath1)
// .setTables("user")
// .setPath(Environment.getExternalStorageDirectory().getPath())
// .setFileName("test.xls")
// .setEncryptKey("1234567")
// .setProtectKey("9876543")
.setEncryptKey("1234567")
.setProtectKey("9876543")
.start(new SQLiteToExcel.ExportListener() {
@Override
public void onStart() {
Expand All @@ -65,6 +67,7 @@ public void onStart() {
public void onCompleted(String filePath) {
tv.append(makeLog("\n" +
"Export completed--->" + filePath));
outputFile = filePath;
}

@Override
Expand All @@ -85,10 +88,11 @@ public void onImport(View v) {

new ExcelToSQLite
.Builder(this)
.setDataBase(databasePath1)
// .setDataBase(databasePath1)
.setAssetFileName("user.xls")
// .setFilePath(Environment.getExternalStorageDirectory().getPath()
// + File.separator + "test.xls")
// .setFilePath(outputFile)
.setDecryptKey("1234567")
.setDateFormat("yyyy-MM-dd HH:mm:ss")
.start(new ExcelToSQLite.ImportListener() {
@Override
public void onStart() {
Expand All @@ -97,10 +101,10 @@ public void onStart() {
}

@Override
public void onCompleted(boolean result) {
public void onCompleted(String result) {
tv.append(makeLog("\n" +
"Import completed--->"));
showDbMsg(databasePath1);
"Import completed--->" + result));
showDbMsg(result);
}

@Override
Expand Down
10 changes: 5 additions & 5 deletions sqlitetoexcel/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ android {
defaultConfig {
minSdkVersion 15
targetSdkVersion 25
versionCode 6
versionName "1.0.5"
versionCode 7
versionName "1.0.6"
}
buildTypes {
release {
Expand All @@ -29,7 +29,7 @@ dependencies {
def siteUrl = 'https://github.com/li-yu/SQLiteToExcel'
def gitUrl = 'https://github.com/li-yu/SQLiteToExcel.git'

version = "1.0.5"
version = "1.0.6"
group = "com.liyu.tools"

Properties properties = new Properties()
Expand All @@ -46,9 +46,9 @@ bintray {
licenses = ["Apache-2.0"]
publish = true
version {
name = '1.0.5'
name = '1.0.6'
released = new Date()
vcsTag = 'v1.0.5'
vcsTag = 'v1.0.6'
attributes = ['gradle-plugin': 'com.use.less:com.use.less.gradle:gradle-useless-plugin']
desc = 'A simple lib for Android to export SQLite to Excel.'
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,24 @@
import android.os.Looper;
import android.text.TextUtils;

import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigInteger;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;

/**
* Excel to SQLite
Expand All @@ -29,15 +36,22 @@ public class ExcelToSQLite {
private static Handler handler = new Handler(Looper.getMainLooper());

private Context mContext;
private String dataBaseName;
private SQLiteDatabase database;
private String filePath;
private String assetFileName;
private String decryptKey;
private String dateFormat;

private SimpleDateFormat sdf;

public static class Builder {
private Context context;
private String dataBaseName;
private String filePath;
private String assetFileName;
private String decryptKey;
private String dateFormat;

public Builder(Context context) {
this.context = context.getApplicationContext();
Expand All @@ -47,23 +61,39 @@ public ExcelToSQLite build() {
if (TextUtils.isEmpty(dataBaseName)) {
throw new IllegalArgumentException("Database name must not be null.");
}
return new ExcelToSQLite(context, dataBaseName, filePath, assetFileName);
return new ExcelToSQLite(context, dataBaseName, filePath, assetFileName, decryptKey, dateFormat);
}

public Builder setDataBase(String dataBaseName) {
this.dataBaseName = dataBaseName;
return this;
}

public Builder setDateFormat(String dateFormat) {
this.dateFormat = dateFormat;
return this;
}

public Builder setFilePath(String path) {
this.filePath = path;
this.assetFileName = null;
if (TextUtils.isEmpty(this.dataBaseName)) {
this.dataBaseName = context.getDatabasePath(new File(path).getName() + ".db").getAbsolutePath();
}
return this;
}

public Builder setDecryptKey(String decryptKey) {
this.decryptKey = decryptKey;
return this;
}

public Builder setAssetFileName(String name) {
this.assetFileName = name;
this.filePath = null;
if (TextUtils.isEmpty(this.dataBaseName)) {
this.dataBaseName = context.getDatabasePath(new File(name).getName() + ".db").getPath();
}
return this;
}

Expand All @@ -79,10 +109,16 @@ public void start(ImportListener listener) {

}

private ExcelToSQLite(Context mContext, String dataBaseName, String filePath, String assetFileName) {
this.mContext = mContext;
private ExcelToSQLite(Context context, String dataBaseName, String filePath, String assetFileName, String decryptKey, String dateFormat) {
this.mContext = context;
this.filePath = filePath;
this.assetFileName = assetFileName;
this.decryptKey = decryptKey;
this.dataBaseName = dataBaseName;
this.dateFormat = dateFormat;
if (!TextUtils.isEmpty(dateFormat)) {
sdf = new SimpleDateFormat(dateFormat);
}

try {
database = SQLiteDatabase.openOrCreateDatabase(dataBaseName, null);
Expand Down Expand Up @@ -137,7 +173,7 @@ public void run() {
handler.post(new Runnable() {
@Override
public void run() {
listener.onCompleted(true);
listener.onCompleted(dataBaseName);
}
});
}
Expand Down Expand Up @@ -168,6 +204,9 @@ public void run() {
private boolean importTables(InputStream stream, String fileName) throws Exception {
Workbook workbook;
if (fileName.toLowerCase().endsWith(".xls")) {
if (!TextUtils.isEmpty(decryptKey)) {
Biff8EncryptionKey.setCurrentUserPassword("1234567");
}
workbook = new HSSFWorkbook(stream);
} else {
throw new UnsupportedOperationException("Unsupported file format!");
Expand Down Expand Up @@ -212,8 +251,17 @@ private void createTable(Sheet sheet) {
continue;
}
if (row.getCell(n).getCellType() == Cell.CELL_TYPE_NUMERIC) {
values.put(columns.get(n), row.getCell(n).getNumericCellValue());
} else {
if (HSSFDateUtil.isCellDateFormatted(row.getCell(n))) {
if (sdf == null) {
values.put(columns.get(n), DateFormat.getDateTimeInstance().format(row.getCell(n).getDateCellValue()));
} else {
values.put(columns.get(n), sdf.format(row.getCell(n).getDateCellValue()));
}
} else {
String value = getRealStringValueOfDouble(row.getCell(n).getNumericCellValue());
values.put(columns.get(n), value);
}
} else if (row.getCell(n).getCellType() == Cell.CELL_TYPE_STRING) {
values.put(columns.get(n), row.getCell(n).getStringCellValue());
}
}
Expand All @@ -226,13 +274,36 @@ private void createTable(Sheet sheet) {
}
}

private static String getRealStringValueOfDouble(Double d) {
String doubleStr = d.toString();
boolean b = doubleStr.contains("E");
int indexOfPoint = doubleStr.indexOf('.');
if (b) {
int indexOfE = doubleStr.indexOf('E');
BigInteger xs = new BigInteger(doubleStr.substring(indexOfPoint
+ BigInteger.ONE.intValue(), indexOfE));
int pow = Integer.valueOf(doubleStr.substring(indexOfE
+ BigInteger.ONE.intValue()));
int xsLen = xs.toByteArray().length;
int scale = xsLen - pow > 0 ? xsLen - pow : 0;
doubleStr = String.format("%." + scale + "f", d);
} else {
java.util.regex.Pattern p = Pattern.compile(".0$");
java.util.regex.Matcher m = p.matcher(doubleStr);
if (m.find()) {
doubleStr = doubleStr.replace(".0", "");
}
}
return doubleStr;
}

/**
* Callbacks for import events.
*/
public interface ImportListener {
void onStart();

void onCompleted(boolean result);
void onCompleted(String dataBaseName);

void onError(Exception e);
}
Expand Down

0 comments on commit f1d6571

Please sign in to comment.