Browse Source

增加excel导出功能

shanmulinxi 2 years ago
parent
commit
8d0a4dd191

+ 2 - 0
app/build.gradle

@@ -88,4 +88,6 @@ dependencies {
 
 
     implementation 'com.liaoinstan.springview:library:1.5.1'
+
+    implementation 'net.sourceforge.jexcelapi:jxl:2.6.12'
 }

+ 12 - 2
app/src/main/java/com/sunwin/visitorapp/SplashActivity.java

@@ -79,9 +79,14 @@ public class SplashActivity extends BaseActivity {
 //        String cert = readExternal(CERT_PATH).trim();
         String cert = SharePrefenceUtils.getString(Constant.ISharePrefence.CERT, "");
         if (TextUtils.isEmpty(cert)) {
-            startAuthActivity();
+            if(BuildConfig.DEBUG){
+                openApplication();
+            }else{
+                startAuthActivity();
+            }
             return;
         }
+
         loadingDialog.showLoadingDialog("授权中,请等待...");
         authApi.authDevice(this.getApplicationContext(), cert, "", new AuthApi.AuthDeviceCallBack() {
             @Override
@@ -104,7 +109,12 @@ public class SplashActivity extends BaseActivity {
                         public void run() {
                             ToastUtils.showToast("Apply update: error. error code is: " + result.errorCode + " , error message: " + result.errorMessage);
                             loadingDialog.dismissLoadingDialog();
-                            startAuthActivity();
+                            if(BuildConfig.DEBUG){
+                                openApplication();
+                            }else{
+                                startAuthActivity();
+                            }
+
                         }
                     });
                 }

+ 4 - 2
app/src/main/java/com/sunwin/visitorapp/db/LogModel.java

@@ -34,13 +34,15 @@ public class LogModel {
 
     public long time;
 
-    public Type type;
+    public final static String Column_Type = "type";
+    @Column(Column_Type)
+    public String type;
 
     public static void AddLog(Type type){
         LogModel model = new LogModel();
         model.name = RunDataManage.GetLoginUser()!=null?RunDataManage.GetLoginUser().name:"未知";
         model.time = new Date().getTime();
-        model.type = type;
+        model.type = type.getName();
         DatabaseManager.getInstance().insertNew(model);
     }
 }

+ 4 - 0
app/src/main/java/com/sunwin/visitorapp/fragment/BlackListManageFr.java

@@ -31,6 +31,7 @@ import com.sunwin.visitorapp.adapter.BaseRecyclerAdapter;
 import com.sunwin.visitorapp.adapter.BaseViewHolder;
 import com.sunwin.visitorapp.db.BlackUserModel;
 import com.sunwin.visitorapp.db.DatabaseManager;
+import com.sunwin.visitorapp.db.LogModel;
 import com.sunwin.visitorapp.db.UserManagerModel;
 import com.sunwin.visitorapp.utils.FileUtil;
 import com.sunwin.visitorapp.utils.ToastUtils;
@@ -64,6 +65,7 @@ public class BlackListManageFr extends Fragment {
             holder.getView(R.id.ButtonDelete).setOnClickListener(v->{
                 new AlertDialog.Builder(context).setTitle("提示").setMessage("确定删除吗?").setPositiveButton("确定", (dialog, which) -> {
                     DatabaseManager.getInstance().delete(data);
+                    LogModel.AddLog(LogModel.Type.BlackListDelete);
                     refreshData();
                 }).setNegativeButton("取消",null).create().show();
             });
@@ -75,6 +77,7 @@ public class BlackListManageFr extends Fragment {
 
 
     private void refreshData(){
+        LogModel.AddLog(LogModel.Type.BlackListSearch);
         adapter.setList(DatabaseManager.getInstance().getQueryAll(BlackUserModel.class));
     }
     @SuppressLint("ResourceAsColor")
@@ -147,6 +150,7 @@ public class BlackListManageFr extends Fragment {
             if(image_uri!=null)
             model.photo = FileUtil.copyToFilesDir(root.getContext(), image_uri);
             DatabaseManager.getInstance().insert(model);
+            LogModel.AddLog(LogModel.Type.BlackListEdit);
             refreshData();
             dialog.dismiss();
         });

+ 43 - 2
app/src/main/java/com/sunwin/visitorapp/fragment/LogManageFr.java

@@ -3,6 +3,7 @@ package com.sunwin.visitorapp.fragment;
 import android.annotation.SuppressLint;
 import android.content.Context;
 import android.os.Bundle;
+import android.os.Environment;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
@@ -23,7 +24,12 @@ import com.sunwin.visitorapp.db.DatabaseManager;
 import com.sunwin.visitorapp.db.LogModel;
 import com.sunwin.visitorapp.db.RoleModel;
 import com.sunwin.visitorapp.db.UserManagerModel;
+import com.sunwin.visitorapp.utils.ExcelUtil;
 import com.sunwin.visitorapp.utils.TimeUtils;
+import com.sunwin.visitorapp.utils.ToastUtils;
+
+import java.io.File;
+import java.util.Date;
 
 public class LogManageFr extends Fragment {
 
@@ -48,7 +54,7 @@ public class LogManageFr extends Fragment {
             public void bind(int position, LogModel data, BaseViewHolder holder, int viewType) {
 
                 holder.setText(R.id.TextName,data.name);
-                holder.setText(R.id.TextType, data.type.getName());
+                holder.setText(R.id.TextType, data.type);
                 holder.setText(R.id.TextTime, TimeUtils.stampToTime(data.time));
 
 
@@ -63,16 +69,51 @@ public class LogManageFr extends Fragment {
         root.findViewById(R.id.ButtonSearch).setOnClickListener(v->{
             search(EditSearchKey.getText().toString().trim());
         });
+
+        root.findViewById(R.id.ButtonExcelOut).setOnClickListener(v->{
+            File sdcard = Environment.getExternalStorageDirectory();
+            String path = new File(sdcard.getAbsolutePath()+"/VisitorAppLog").getAbsolutePath();
+            String excelFileName = "/日志记录"+TimeUtils.stampToTime(new Date().getTime())+".xls";
+            new AlertDialog.Builder(context).setTitle("提示").setMessage("确定导出吗?将"+adapter.getList().size()+"条数据导出到\n"+path+excelFileName).setPositiveButton("确定", (dialog, which) -> {
+                OntExcel(path,excelFileName);
+            }).setNegativeButton("取消",null).create().show();
+
+        });
         return root;
     }
 
+
+    public void OntExcel(String path,String fileName) {
+
+        new Thread(() -> {
+            try {
+                File file = new File(path);
+                if (!file.exists()) {
+                    file.mkdirs();
+                }
+                String[] title = {"用户名称", "操作类型", "操作时间"};
+                String sheetName = "日志记录";
+                String filePaths = file.getAbsolutePath() + fileName;
+                ExcelUtil.initExcel(filePaths, sheetName, title);
+                ExcelUtil.writeObjListToExcel(adapter.getList(), filePaths, LogManageFr.this.requireActivity());
+                LogManageFr.this.requireActivity().runOnUiThread(() -> ToastUtils.showToast("导出成功"));
+                return;
+            }catch (Exception ig){
+                LogManageFr.this.requireActivity().runOnUiThread(() -> ToastUtils.showToast("导出失败"));
+            }
+
+        }).start();
+
+    }
     private void refreshData(){
         adapter.setList(DatabaseManager.getInstance().getQueryAll(LogModel.class));
     }
 
     private void search(String key){
         QueryBuilder<LogModel> q =new QueryBuilder<>(LogModel.class);
-        q.whereEquals(LogModel.Column_Name,key);
+        q.where(LogModel.Column_Name + " like ?","%"+key+"%")
+        .whereAppendOr().where(LogModel.Column_Type+ " like ?","%"+key+"%");
+
         adapter.setList(DatabaseManager.getInstance().query(q));
     }
 }

+ 5 - 0
app/src/main/java/com/sunwin/visitorapp/fragment/RoleManageFr.java

@@ -27,6 +27,7 @@ import com.sunwin.visitorapp.adapter.BaseRecyclerAdapter;
 import com.sunwin.visitorapp.adapter.BaseViewHolder;
 import com.sunwin.visitorapp.db.BlackUserModel;
 import com.sunwin.visitorapp.db.DatabaseManager;
+import com.sunwin.visitorapp.db.LogModel;
 import com.sunwin.visitorapp.db.RoleModel;
 import com.sunwin.visitorapp.db.UserManagerModel;
 import com.sunwin.visitorapp.manage.RunDataManage;
@@ -62,6 +63,7 @@ public class RoleManageFr extends Fragment {
                 holder.getView(R.id.ButtonDelete).setOnClickListener(v->{
                     new AlertDialog.Builder(holder.itemView.getContext()).setTitle("提示").setMessage("确定删除吗?").setPositiveButton("确定", (dialog, which) -> {
                         DatabaseManager.getInstance().delete(data);
+                        LogModel.AddLog(LogModel.Type.RoleDelete);
                         refreshData();
                     }).setNegativeButton("取消",null).create().show();
                 });
@@ -85,9 +87,11 @@ public class RoleManageFr extends Fragment {
         return root;
     }
     private void refreshData(){
+        LogModel.AddLog(LogModel.Type.RoleSearch);
         adapter.setList(DatabaseManager.getInstance().getQueryAll(RoleModel.class));
     }
     private void search(String key){
+        LogModel.AddLog(LogModel.Type.RoleSearch);
         adapter.setList(DatabaseManager.getInstance().getQueryByWhere(RoleModel.class,"name",key));
     }
     private void createDialog(Context context, ViewGroup parent, RoleModel model){
@@ -128,6 +132,7 @@ public class RoleManageFr extends Fragment {
             model.p_visitor_sign_in = CheckVisitorSignIn.isChecked();
             model.p_visitor_sign_out = CheckVisitorSignOut.isChecked();
             DatabaseManager.getInstance().save(model);
+            LogModel.AddLog(LogModel.Type.RoleEdit);
             if(RunDataManage.GetLoginRole()!=null&&RunDataManage.GetLoginRole().id==model.id){
                 RunDataManage.RefreshLoginUser();
             }

+ 5 - 0
app/src/main/java/com/sunwin/visitorapp/fragment/UserManageFr.java

@@ -34,6 +34,7 @@ import com.sunwin.visitorapp.R;
 import com.sunwin.visitorapp.adapter.BaseRecyclerAdapter;
 import com.sunwin.visitorapp.adapter.BaseViewHolder;
 import com.sunwin.visitorapp.db.DatabaseManager;
+import com.sunwin.visitorapp.db.LogModel;
 import com.sunwin.visitorapp.db.RoleModel;
 import com.sunwin.visitorapp.db.UserManagerModel;
 import com.sunwin.visitorapp.manage.RunDataManage;
@@ -79,6 +80,7 @@ public class UserManageFr extends Fragment {
                 });
                 holder.getView(R.id.ButtonDelete).setOnClickListener(v->{
                     new AlertDialog.Builder(context).setTitle("提示").setMessage("确定删除吗?").setPositiveButton("确定", (dialog, which) -> {
+                        LogModel.AddLog(LogModel.Type.UserDelete);
                         DatabaseManager.getInstance().delete(data);
                         refreshData();
                     }).setNegativeButton("取消",null).create().show();
@@ -101,10 +103,12 @@ public class UserManageFr extends Fragment {
     }
 
     private void refreshData(){
+        LogModel.AddLog(LogModel.Type.UserSearch);
         adapter.setList(DatabaseManager.getInstance().getQueryAll(UserManagerModel.class));
     }
 
     private void search(String key){
+        LogModel.AddLog(LogModel.Type.UserSearch);
         adapter.setList(DatabaseManager.getInstance().getQueryByWhere(UserManagerModel.class,"name",key));
     }
 
@@ -238,6 +242,7 @@ public class UserManageFr extends Fragment {
 //            model.valid_time = TextValidTime.getText().toString().trim();
             Timber.e(GsonUtil.toJson(model));
             DatabaseManager.getInstance().save(model);
+            LogModel.AddLog(LogModel.Type.UserEdit);
             if(RunDataManage.GetLoginUser()!=null&&RunDataManage.GetLoginUser().id==model.id){
                 RunDataManage.RefreshLoginUser();
             }

+ 171 - 0
app/src/main/java/com/sunwin/visitorapp/utils/ExcelUtil.java

@@ -0,0 +1,171 @@
+package com.sunwin.visitorapp.utils;
+
+import android.content.Context;
+
+import com.sunwin.visitorapp.db.LogModel;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.List;
+
+import jxl.Workbook;
+import jxl.WorkbookSettings;
+import jxl.format.Colour;
+import jxl.write.Label;
+import jxl.write.WritableCell;
+import jxl.write.WritableCellFormat;
+import jxl.write.WritableFont;
+import jxl.write.WritableSheet;
+import jxl.write.WritableWorkbook;
+import jxl.write.WriteException;
+
+public class ExcelUtil {
+    private static WritableFont arial14font = null;
+
+    private static WritableCellFormat arial14format = null;
+    private static WritableFont arial10font = null;
+    private static WritableCellFormat arial10format = null;
+    private static WritableFont arial12font = null;
+    private static WritableCellFormat arial12format = null;
+    private final static String UTF8_ENCODING = "UTF-8";
+
+
+    /**
+     * 单元格的格式设置 字体大小 颜色 对齐方式、背景颜色等...
+     */
+    private static void format() {
+        try {
+            arial14font = new WritableFont(WritableFont.ARIAL, 14, WritableFont.BOLD);
+            arial14font.setColour(Colour.LIGHT_BLUE);
+            arial14format = new WritableCellFormat(arial14font);
+            arial14format.setAlignment(jxl.format.Alignment.CENTRE);
+            arial14format.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
+            arial14format.setBackground(Colour.VERY_LIGHT_YELLOW);
+
+            arial10font = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD);
+            arial10format = new WritableCellFormat(arial10font);
+            arial10format.setAlignment(jxl.format.Alignment.CENTRE);
+            arial10format.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
+            arial10format.setBackground(Colour.GRAY_25);
+
+            arial12font = new WritableFont(WritableFont.ARIAL, 10);
+            arial12format = new WritableCellFormat(arial12font);
+            //对齐格式
+            arial10format.setAlignment(jxl.format.Alignment.CENTRE);
+            //设置边框
+            arial12format.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
+
+        } catch (WriteException e) {
+            e.printStackTrace();
+        }
+    }
+
+
+    /**
+     * 初始化Excel表格
+     *
+     * @param filePath  存放excel文件的路径(path/demo.xls)
+     * @param sheetName Excel表格的表名
+     * @param colName   excel中包含的列名(可以有多个)
+     */
+    public static void initExcel(String filePath, String sheetName, String[] colName) {
+        format();
+        WritableWorkbook workbook = null;
+        try {
+            File file = new File(filePath);
+            if (!file.exists()) {
+                file.createNewFile();
+            } else {
+                return;
+            }
+            workbook = Workbook.createWorkbook(file);
+            //设置表格的名字
+            WritableSheet sheet = workbook.createSheet(sheetName, 0);
+            //创建标题栏
+            sheet.addCell((WritableCell) new Label(0, 0, filePath, arial14format));
+            for (int col = 0; col < colName.length; col++) {
+                sheet.addCell(new Label(col, 0, colName[col], arial10format));
+            }
+            //设置行高
+            sheet.setRowView(0, 340);
+            workbook.write();
+        } catch (Exception e) {
+            e.printStackTrace();
+        } finally {
+            if (workbook != null) {
+                try {
+                    workbook.close();
+                } catch (Exception e) {
+                    e.printStackTrace();
+                }
+            }
+        }
+    }
+
+    /**
+     * 将制定类型的List写入Excel中
+     *
+     */
+    @SuppressWarnings("unchecked")
+    public static  void writeObjListToExcel(List<LogModel> objList, String fileName, Context mContext) {
+        if (objList != null && objList.size() > 0) {
+            WritableWorkbook writebook = null;
+            InputStream in = null;
+            try {
+                WorkbookSettings setEncode = new WorkbookSettings();
+                setEncode.setEncoding(UTF8_ENCODING);
+
+                in = new FileInputStream(new File(fileName));
+                Workbook workbook = Workbook.getWorkbook(in);
+                writebook = Workbook.createWorkbook(new File(fileName), workbook);
+                WritableSheet sheet = writebook.getSheet(0);
+
+                for (int j = 0; j < objList.size(); j++) {
+                    LogModel demoBean = (LogModel) objList.get(j);
+                    List<String> list = new ArrayList<>();
+                    list.add(demoBean.name);
+                    list.add(demoBean.type);
+                    list.add(TimeUtils.stampToTime(demoBean.time));
+
+                    for (int i = 0; i < list.size(); i++) {
+                        sheet.addCell(new Label(i, j + 1, list.get(i), arial12format));
+                        if (list.get(i).length() <= 4) {
+                            //设置列宽
+                            sheet.setColumnView(i, list.get(i).length() + 8);
+                        } else {
+                            //设置列宽
+                            sheet.setColumnView(i, list.get(i).length() + 5);
+                        }
+                    }
+                    //设置行高
+                    sheet.setRowView(j + 1, 350);
+                }
+
+                writebook.write();
+                workbook.close();
+            } catch (Exception e) {
+                e.printStackTrace();
+            } finally {
+                if (writebook != null) {
+                    try {
+                        writebook.close();
+                    } catch (Exception e) {
+                        e.printStackTrace();
+                    }
+
+                }
+                if (in != null) {
+                    try {
+                        in.close();
+                    } catch (IOException e) {
+                        e.printStackTrace();
+                    }
+                }
+            }
+
+        }
+    }
+}

+ 2 - 0
app/src/main/res/layout/fr_log_manage.xml

@@ -11,6 +11,7 @@
         android:layout_width="match_parent"
         android:layout_height="wrap_content">
         <Button
+            android:id="@+id/ButtonExcelOut"
             style="@style/ButtonPrimaryLarge"
 
             app:layout_constraintStart_toStartOf="parent"
@@ -54,6 +55,7 @@
                 style="@style/StyleInputContent"
                 android:layout_height="wrap_content"/>
             <Button
+                android:id="@+id/ButtonSearch"
                 style="@style/ButtonPrimaryLarge"
                 android:layout_width="wrap_content"
                 android:textAlignment="center"