SQLite에서 excel android로 전환

101781 단어 안드로이드 개발
SQLite에서 excel android로 전환
  • 처음 블로그를 썼는데 잘 못 썼으니 양해해 주십시오
  • 휠을 훔쳤다
  • 코드 붙인다
  • 코드는 대략 이렇다. 레이아웃은 단추 세 개와 TextView 세 개다.필요한 건 GitHub에 가보세요
  • 가능하면 이 작은 앱
  • 을 지원해 주세요.
  • 아 죄송합니다.자신의 소프트웨어를 완전히 역컴파일하지 않아서 올린 그 파일은 설치할 수 없는 앱이니 다운로드하지 마세요.정상적인 app가 GitHub에 다시 업로드됨
  • 처음 블로그를 쓰는데 잘 못 쓴 점 양해해 주십시오
    동창이 갑자기 안드로이드에서 데이터베이스 파일을 열 수 있느냐고 물었다.지난번 프로젝트를 할 때 SQLite 로컬 저장소를 사용해야 했는데 핸드폰으로 대응하는 데이터베이스 파일을 열 수 없어서 고생했다고 생각합니다.시작% &%...%...% & (
    바퀴를 훔쳤다
    GitHub에는 앱의 특정 데이터베이스를 가져와 조작하는 것이 있다.그 중의 데이터를cursor로 읽고 표를 삽입합니다.https://github.com/androidmads/SQLite2XL자신의 수요를 위해 저는 개선을 했습니다. 데이터베이스 대상을 선택하고 전환을 했습니다.
  • 로컬 파일을 선택하면 app가 자신의 내부 파일을 조작하기 쉽기 때문에 저는 이곳에서 원래의 데이터베이스 파일을 복사하여 본 app의 데이터베이스 폴더에 넣었습니다.여기서 나는 원래의 데이터베이스 경로를old 라고 부른다path, 복사된 새 디렉터리는 newpath.
  • 변환은 로컬 데이터베이스 폴더 아래의 데이터베이스를 변환합니다.데이터베이스에 있는 파일을 커서로 가져와 한 줄 한 줄 표에 쓰는 것이다.
  • 생성된 표 열기
  • 코드 붙일게요.
  • manifest.xml: 권한 가져오기
  •  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    
  • gradle: 의존 추가
  •     implementation 'org.apache.poi:poi:3.16'
        implementation 'com.android.support:design:28.0.0'
    
  • MainActivity.java
  • import android.content.Intent;
    import android.net.Uri;
    import android.os.Environment;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;
    
    import android.annotation.SuppressLint;
    import android.app.Activity;
    import android.os.Build;
    import android.widget.Toast;
    
    import java.io.File;
    import java.io.IOException;
    import static com.butterfly.sqltest.FileUtil.copyFileUsingFileChannels;
    
    public class MainActivity extends AppCompatActivity {
        TextView db_old_path;
        TextView db_new_path;
        TextView excel;
        Button open_db;
        Button change_btn;
        Button open_excel_btn;
    
        String old_path;
        String new_path;
    
        @SuppressLint("SdCardPath")
        String db_path="/data/data/com.butterfly.sqltest/databases/";
        String db_name;
    
        private String excel_name="db.xls";//     
        String excel_path = Environment.getExternalStorageDirectory().getPath()+"/backup/";//      
    
        SQLiteToExcel sqliteToExcel;
        boolean isChange=false;//           
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            open_db = findViewById(R.id.open_db);
            change_btn=findViewById(R.id.change_btn);
            open_excel_btn=findViewById(R.id.open_excel_btn);
            db_old_path =  findViewById(R.id.db_old_path);
            db_new_path =  findViewById(R.id.db_new_path);
            excel = findViewById(R.id.excel_path);
    
            open_db.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    isChange=true;
                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.setType("*/*");//     
                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                    startActivityForResult(intent, 1);
                }
            });
    
            change_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(isChange==true)
                        change(v);
                }
            });
    
            open_excel_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
    
                    Intent intent = new Intent("android.intent.action.VIEW");
                    intent.addCategory("android.intent.category.DEFAULT");
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    Uri uri = Uri.fromFile(new File(excel_path+excel_name ));
                    intent.setDataAndType(uri, "application/vnd.ms-excel");
    
                    startActivity(intent);
                }
            });
    
        }
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (resultCode == Activity.RESULT_OK) {
                Uri uri = data.getData();
                if ("file".equalsIgnoreCase(uri.getScheme())){//         
                    old_path = uri.getPath();
                    db_old_path.setText(old_path);
                    Toast.makeText(this,old_path+"11111",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {//4.4  
                    old_path = FileUtil.getPath(this, uri);
                    db_old_path.setText("        :"+old_path);
    
                    Toast.makeText(this,old_path,Toast.LENGTH_SHORT).show();
                } else {//4.4         
                    old_path = FileUtil.getRealPathFromURI(this,uri);
                    db_old_path.setText(old_path);
                    Toast.makeText(MainActivity.this, old_path+"222222", Toast.LENGTH_SHORT).show();
                }
                File file=new File(old_path);
                db_name=file.getName();
                new_path=db_path+db_name;
                db_new_path.setText("      :"+new_path);
                excel.setText("      :"+excel_path+excel_name);
                try {//copyFileUsingFileChannels(new File(old_path),new File(new_path));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
        public void change(final View view){
    
            sqliteToExcel = new SQLiteToExcel(getApplicationContext(), db_name, excel_path);
    
            sqliteToExcel.exportAllTables(excel_name, new SQLiteToExcel.ExportListener() {
                @Override
                public void onStart() {
    
                }
    
                @Override
                public void onCompleted(String filePath) {
                    Utils.showSnackBar(view, "Successfully Exported");
                }
    
                @Override
                public void onError(Exception e) {
                    Utils.showSnackBar(view, e.getMessage());
                }
            });
        }
    }
    
  • SQLiteToExcel.java
  • 
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.os.Handler;
    import android.os.Looper;
    import org.apache.poi.hssf.usermodel.HSSFCell;
    import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
    import org.apache.poi.hssf.usermodel.HSSFPatriarch;
    import org.apache.poi.hssf.usermodel.HSSFRichTextString;
    import org.apache.poi.hssf.usermodel.HSSFRow;
    import org.apache.poi.hssf.usermodel.HSSFSheet;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.ss.usermodel.ClientAnchor;
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    
    public class SQLiteToExcel {
    
        private static Handler handler = new Handler(Looper.getMainLooper());
    
        private SQLiteDatabase database;
        private String mExportPath;
        private HSSFWorkbook workbook;
    
        private List<String> mExcludeColumns = null;
        private HashMap<String, String> mPrettyNameMapping = null;
        private ExportCustomFormatter mCustomFormatter = null;
    
        public SQLiteToExcel(Context context, String dbName, String exportPath) {
            mExportPath = exportPath;
            try {
                database = SQLiteDatabase.openOrCreateDatabase(context.getDatabasePath(dbName).getAbsolutePath(), null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
    
    
        private ArrayList<String> getAllTables() {
            ArrayList<String> tables = new ArrayList<>();
            Cursor cursor = database.rawQuery("select name from sqlite_master where type='table' order by name", null);
            while (cursor.moveToNext()) {
                tables.add(cursor.getString(0));
            }
            cursor.close();
            return tables;
        }
    
        private ArrayList<String> getColumns(String table) {
            ArrayList<String> columns = new ArrayList<>();
            Cursor cursor = database.rawQuery("PRAGMA table_info(" + table + ")", null);
            while (cursor.moveToNext()) {
                columns.add(cursor.getString(1));
            }
            cursor.close();
            return columns;
        }
    
        private void exportTables(List<String> tables, final String fileName) throws Exception {
            workbook = new HSSFWorkbook();
            for (int i = 0; i < tables.size(); i++) {
                if (!tables.get(i).equals("android_metadata")) {
                    HSSFSheet sheet = workbook.createSheet(prettyNameMapping(tables.get(i)));
                    createSheet(tables.get(i), sheet);
                }
            }
            File file = new File(mExportPath, fileName);
            FileOutputStream fos = new FileOutputStream(file);
            workbook.write(fos);
            fos.flush();
            fos.close();
            workbook.close();
            database.close();
        }
    
    
        public void exportAllTables(final String fileName, ExportListener listener) {
            ArrayList<String> tables = getAllTables();
            startExportTables(tables, fileName, listener);
        }
    
        private void startExportTables(final List<String> tables, final String fileName, final ExportListener listener) {
            if (listener != null) {
                listener.onStart();
            }
            new Thread(new Runnable() {
    
                @Override
                public void run() {
                    try {
                        exportTables(tables, fileName);
                        if (listener != null) {
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    listener.onCompleted(mExportPath + fileName);
                                }
                            });
                        }
                    } catch (final Exception e) {
                        if (database != null && database.isOpen()) {
                            database.close();
                        }
                        if (listener != null)
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    listener.onError(e);
                                }
                            });
                    }
                }
            }).start();
        }
    
        private void createSheet(String table, HSSFSheet sheet) {
            HSSFRow rowA = sheet.createRow(0);
            ArrayList<String> columns = getColumns(table);
            int cellIndex = 0;
            for (int i = 0; i < columns.size(); i++) {
                String columnName = prettyNameMapping("" + columns.get(i));
                if (!excludeColumn(columnName)) {
                    HSSFCell cellA = rowA.createCell(cellIndex);
                    cellA.setCellValue(new HSSFRichTextString(columnName));
                    cellIndex++;
                }
            }
            insertItemToSheet(table, sheet, columns);
        }
    
        private void insertItemToSheet(String table, HSSFSheet sheet, ArrayList<String> columns) {
            HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
            Cursor cursor = database.rawQuery("select * from " + table, null);
            cursor.moveToFirst();
            int n = 1;
            while (!cursor.isAfterLast()) {
                HSSFRow rowA = sheet.createRow(n);
                int cellIndex = 0;
                for (int j = 0; j < columns.size(); j++) {
                    String columnName = "" + columns.get(j);
                    if (!excludeColumn(columnName)) {
                        HSSFCell cellA = rowA.createCell(cellIndex);
                        if (cursor.getType(j) == Cursor.FIELD_TYPE_BLOB) {
                            HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, (short) cellIndex, n, (short) (cellIndex + 1), n + 1);
                            anchor.setAnchorType(ClientAnchor.AnchorType.DONT_MOVE_AND_RESIZE);
                            patriarch.createPicture(anchor, workbook.addPicture(cursor.getBlob(j), HSSFWorkbook.PICTURE_TYPE_JPEG));
                        } else {
                            String value = cursor.getString(j);
                            if (null != mCustomFormatter) {
                                value = mCustomFormatter.process(columnName, value);
                            }
                            cellA.setCellValue(new HSSFRichTextString(value));
                        }
                        cellIndex++;
                    }
                }
                n++;
                cursor.moveToNext();
            }
            cursor.close();
        }
    
        /**
         * Do we exclude the specified column from the export
         *
         * @param column
         * @return boolean
         */
        private boolean excludeColumn(String column) {
            boolean exclude = false;
            if (null != mExcludeColumns) {
                return mExcludeColumns.contains(column);
            }
    
            return exclude;
        }
    
        /**
         * Convert the specified name to a `pretty` name if a mapping exists
         *
         * @param name
         * @return
         */
        private String prettyNameMapping(String name) {
            if (null != mPrettyNameMapping) {
                if (mPrettyNameMapping.containsKey(name)) {
                    name = mPrettyNameMapping.get(name);
                }
            }
            return name;
        }
    
        public interface ExportListener {
            void onStart();
    
            void onCompleted(String filePath);
    
            void onError(Exception e);
        }
    
        /**
         * Interface class for the custom formatter
         */
        public interface ExportCustomFormatter {
            String process(String columnName, String value);
        }
    }
    
  • FileUtil 파일 작업
  • import android.annotation.SuppressLint;
    import android.content.ContentUris;
    import android.content.Context;
    import android.database.Cursor;
    import android.net.Uri;
    import android.os.Build;
    import android.os.Environment;
    import android.provider.DocumentsContract;
    import android.provider.MediaStore;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.nio.channels.FileChannel;
    
    public class FileUtil {
    
        public static String getRealPathFromURI(final Context context, Uri contentUri) {
            String res = null;
            String[] proj = { MediaStore.Images.Media.DATA };
            Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
            if(null!=cursor&&cursor.moveToFirst()){
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                res = cursor.getString(column_index);
                cursor.close();
            }
            return res;
        }
    
        /**
         *   Android4.4    Uri        ,         
         */
        @SuppressLint("NewApi")
        public static String getPath(final Context context, final Uri uri) {
    
            final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
    
            // DocumentProvider
            if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
                // ExternalStorageProvider
                if (isExternalStorageDocument(uri)) {
                    final String docId = DocumentsContract.getDocumentId(uri);
                    final String[] split = docId.split(":");
                    final String type = split[0];
    
                    if ("primary".equalsIgnoreCase(type)) {
                        return Environment.getExternalStorageDirectory() + "/" + split[1];
                    }
                }
                // DownloadsProvider
                else if (isDownloadsDocument(uri)) {
    
                    final String id = DocumentsContract.getDocumentId(uri);
                    final Uri contentUri = ContentUris.withAppendedId(
                            Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
    
                    return getDataColumn(context, contentUri, null, null);
                }
                // MediaProvider
                else if (isMediaDocument(uri)) {
                    final String docId = DocumentsContract.getDocumentId(uri);
                    final String[] split = docId.split(":");
                    final String type = split[0];
    
                    Uri contentUri = null;
                    if ("image".equals(type)) {
                        contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                    } else if ("video".equals(type)) {
                        contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                    } else if ("audio".equals(type)) {
                        contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                    }
    
                    final String selection = "_id=?";
                    final String[] selectionArgs = new String[]{split[1]};
    
                    return getDataColumn(context, contentUri, selection, selectionArgs);
                }
            }
            // MediaStore (and general)
            else if ("content".equalsIgnoreCase(uri.getScheme())) {
                return getDataColumn(context, uri, null, null);
            }
            // File
            else if ("file".equalsIgnoreCase(uri.getScheme())) {
                return uri.getPath();
            }
            return null;
        }
    
        /**
         * Get the value of the data column for this Uri. This is useful for
         * MediaStore Uris, and other file-based ContentProviders.
         *
         * @param context       The context.
         * @param uri           The Uri to query.
         * @param selection     (Optional) Filter used in the query.
         * @param selectionArgs (Optional) Selection arguments used in the query.
         * @return The value of the _data column, which is typically a file old_path.
         */
        public static String getDataColumn(Context context, Uri uri, String selection,
                                           String[] selectionArgs) {
    
            Cursor cursor = null;
            final String column = "_data";
            final String[] projection = {column};
    
            try {
                cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                        null);
                if (cursor != null && cursor.moveToFirst()) {
                    final int column_index = cursor.getColumnIndexOrThrow(column);
                    return cursor.getString(column_index);
                }
            } finally {
                if (cursor != null)
                    cursor.close();
            }
            return null;
        }
    
        /**
         * @param uri The Uri to check.
         * @return Whether the Uri authority is ExternalStorageProvider.
         */
        public static boolean isExternalStorageDocument(Uri uri) {
            return "com.android.externalstorage.documents".equals(uri.getAuthority());
        }
    
        /**
         * @param uri The Uri to check.
         * @return Whether the Uri authority is DownloadsProvider.
         */
        public static boolean isDownloadsDocument(Uri uri) {
            return "com.android.providers.downloads.documents".equals(uri.getAuthority());
        }
    
        /**
         * @param uri The Uri to check.
         * @return Whether the Uri authority is MediaProvider.
         */
        public static boolean isMediaDocument(Uri uri) {
            return "com.android.providers.media.documents".equals(uri.getAuthority());
        }
    
        public static void copyFileUsingFileChannels(File source, File dest) throws IOException {
            FileChannel inputChannel = null;
            FileChannel outputChannel = null;
            try {
                inputChannel = new FileInputStream(source).getChannel();
                outputChannel = new FileOutputStream(dest).getChannel();
                outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
            } finally {
                inputChannel.close();
                outputChannel.close();
            }
        }
    
    }
    
    

    코드는 대략 이렇다. 레이아웃은 단추 세 개와 TextView 세 개다.필요한 건 GitHub에 가보세요.
    https://github.com/ButterflyXiao/SQLToExcel
    가능하면 이 작은 앱을 지원해 주세요.
    https://download.csdn.net/download/qq_36317491/10791103
    죄송합니다.자신의 소프트웨어를 완전히 역컴파일하지 않아서 올린 그 파일은 설치할 수 없는 앱이니 다운로드하지 마세요.정상적인 앱이 GitHub에 다시 업로드됨

    좋은 웹페이지 즐겨찾기