1. 程式人生 > >[Android]匯入匯出Excel表格到本地SQLite

[Android]匯入匯出Excel表格到本地SQLite

[Android]匯入匯出Excel表格到SQLite

@Author GQ 20161116日  

最近郭神出了LitePal的新版本,感覺好用的不要不要的,匯入資料的時候每次都要手寫新增,不如直接用excel匯入方便多了.

效果圖

  • 需要匯入的excel資源,自己隨便寫的,只有學號和學生姓名兩列

這裡寫圖片描述

  • 匯入後

這裡寫圖片描述

查閱資料後,發現有 jxl 和 poi 兩種, 貌似前者不太受歡迎了,所以這裡記錄POI方式:

1. AndroidStudio使用

//匯入jar包
dependencies {

    compile files('libs/poi-3.15.jar'
) compile 'org.litepal.android:core:1.4.0' }

2. 使用

  • POI:

HSSF - 提供讀寫Microsoft Excel XLS格式檔案的功能。  

XSSF - 提供讀寫Microsoft Excel OOXML XLSX格式檔案的功能。  

HWPF - 提供讀寫Microsoft Word DOC格式檔案的功能。  

HSLF - 提供讀寫Microsoft PowerPoint格式檔案的功能。  

HDGF - 提供讀Microsoft Visio格式檔案的功能。  

HPBF - 提供讀Microsoft Publisher格式檔案的功能。  

HSMF - 提供讀Microsoft Outlook格式檔案的功能。

//fileChooser介面就省略了,直接呼叫系統的檔案管理,觸發事件
...

//匯入格式為 .xls .xlsx
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("application/*");//設定型別
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, 1);


//然後進入系統的檔案管理,選擇檔案後
@Override
    protected
void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK && data != null) { LogUtil.e(TAG, "選擇的檔案Uri = " + data.toString()); //通過Uri獲取真實路徑 final String excelPath = getRealFilePath(this, data.getData()); LogUtil.e(TAG, "excelPath = " + excelPath);// /storage/emulated/0/test.xls if (excelPath.contains(".xls") || excelPath.contains(".xlsx")) { showSnack("正在載入Excel中..."); //載入excel readExcel(excelPath); } else { showSnack("此檔案不是excel格式"); } } } //讀取Excel表 private void readExcel(String excelPath) { try { InputStream input = new FileInputStream(new File(excelPath)); POIFSFileSystem fs = new POIFSFileSystem(input); HSSFWorkbook wb = new HSSFWorkbook(fs); HSSFSheet sheet = wb.getSheetAt(0); // Iterate over each row in the sheet Iterator<Row> rows = sheet.rowIterator(); while (rows.hasNext()) { HSSFRow row = (HSSFRow) rows.next(); System.out.println("Row #" + row.getRowNum()); //每一行 = 新建一個學生 Student stu = new Student(); // Iterate over each cell in the row and print out the cell"s // content Iterator<Cell> cells = row.cellIterator(); while (cells.hasNext()) { HSSFCell cell = (HSSFCell) cells.next(); switch (cell.getCellType()) { case HSSFCell.CELL_TYPE_NUMERIC: System.out.println("number= " + (int) (cell.getNumericCellValue())); //自定操作,我這裡寫入學號 stu.setSno((int) (cell.getNumericCellValue()) + ""); break; case HSSFCell.CELL_TYPE_STRING: System.out.println("string= " + cell.getStringCellValue()); //自定操作,我這裡寫入姓名 stu.setName(cell.getStringCellValue()); break; case HSSFCell.CELL_TYPE_BOOLEAN: System.out.println("boolean= " + cell.getBooleanCellValue()); break; case HSSFCell.CELL_TYPE_FORMULA: System.out.println("formula= " + cell.getCellFormula()); break; default: System.out.println("unsuported sell type"); break; } } stu.save(); } } catch (IOException ex) { ex.printStackTrace(); } //重新整理列表 getAllStudent(); } //查詢所有學生 private void getAllStudent() { studentList = DataSupport.findAll(Student.class); } /** * 根據Uri獲取真實圖片路徑 * <p/> * 一個android檔案的Uri地址一般如下: * content://media/external/images/media/62026 * * @param context * @param uri * @return */ public static String getRealFilePath(final Context context, final Uri uri) { if (null == uri) return null; final String scheme = uri.getScheme(); String data = null; if (scheme == null) data = uri.getPath(); else if (ContentResolver.SCHEME_FILE.equals(scheme)) { data = uri.getPath(); } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) { Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null); if (null != cursor) { if (cursor.moveToFirst()) { int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); if (index > -1) { data = cursor.getString(index); } } cursor.close(); } } return data; }
//資料匯出到excel
String ROOT_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + getResources().getString(R.string.app_name) + "/";

    public void writeExcel(String exFileName, String sheetName) {
        try {
            File dir = new File(ROOT_PATH);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            String exPath = ROOT_PATH + exFileName + ".xls";
            File file = new File(exPath);
            file.createNewFile();
            OutputStream out = new FileOutputStream(file);

            //新建excel
            HSSFWorkbook workBook = new HSSFWorkbook();

            //新建sheet
            HSSFSheet sheet = workBook.createSheet(sheetName);

            //建立單元格樣式
            HSSFCellStyle style = getStyle(workBook);

            for (int i = 0; i < adapterList.size(); i++) {
                //建立行
                HSSFRow row = sheet.createRow(i);
                ListInfo info = adapterList.get(i);
                for (int j = 0; j < 13; j++) {
                    //建立列單元格
                    HSSFCell cell = row.createCell(j);
                    cell.setCellStyle(style);
                    switch (j) {
                        case 0://時間
                            cell.setCellValue(info.getTiem());
                            break;
                        case 1:
                            cell.setCellValue(info.getWq());
                            break;
                        case 2:
                            cell.setCellValue(info.getWb());
                            break;
                        case 3:
                            cell.setCellValue(info.getWs());
                            break;
                        case 4:
                            cell.setCellValue(info.getWg());
                            break;
                        case 5:
                            cell.setCellValue(info.getWq());
                            break;
                        case 6:
                            cell.setCellValue(info.getQb());
                            break;
                        case 7:
                            cell.setCellValue(info.getQs());
                            break;
                        case 8:
                            cell.setCellValue(info.getQg());
                            break;
                        case 9:
                            cell.setCellValue(info.getBs());
                            break;
                        case 10:
                            cell.setCellValue(info.getBg());
                            break;
                        case 11:
                            cell.setCellValue(info.getSg());
                            break;
                        case 12://號碼
                            cell.setCellValue(info.getCode());
                            break;
                    }

                    //合併單元格,引數是起始行,結束行,起始列,結束列
//                    sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex + 1, i, i));
                }
            }

            workBook.write(out);

            out.flush();
            out.close();
            showShortToast("Excel檔案儲存到 :" + ROOT_PATH);
        } catch (Exception e) {
            e.printStackTrace();
            showShortToast("Excel檔案" + exFileName + "生成失敗:" + e);
        }
    }


    public HSSFCellStyle getStyle(HSSFWorkbook workbook) {

        //設定樣式;
        HSSFCellStyle style = workbook.createCellStyle();
        //設定底邊框;
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        //設定底邊框顏色;
        style.setBottomBorderColor(HSSFColor.BLACK.index);
        //設定左邊框;
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        //設定左邊框顏色;
        style.setLeftBorderColor(HSSFColor.BLACK.index);
        //設定右邊框;
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        //設定右邊框顏色;
        style.setRightBorderColor(HSSFColor.BLACK.index);
        //設定頂邊框;
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        //設定頂邊框顏色;
        style.setTopBorderColor(HSSFColor.BLACK.index);
        //設定自動換行;
        style.setWrapText(false);
        //設定水平對齊的樣式為居中對齊;
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        //設定垂直對齊的樣式為居中對齊;
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        // 設定單元格字型
        HSSFFont font = workbook.createFont();
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        font.setFontName("宋體");
        font.setFontHeight((short) 200);
        style.setFont(font);

        return style;
    }
  • 注: 這裡匯入匯出都是用的excel2003 (使用2007的每次都報錯,暫時沒有解決)

```java
//intent.setType("*/*")格式大全


    {".3gp",    "video/3gpp"},
    {".apk",    "application/vnd.android.package-archive"},
    {".asf",    "video/x-ms-asf"},
    {".avi",    "video/x-msvideo"},
    {".bin",    "application/octet-stream"},
    {".bmp",    "image/bmp"},
    {".c",  "text/plain"},
    {".class",  "application/octet-stream"},
    {".conf",   "text/plain"},
    {".cpp",    "text/plain"},
    {".doc",    "application/msword"},
    {".docx",   "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
    {".xls",    "application/vnd.ms-excel"},
    {".xlsx",   "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
    {".exe",    "application/octet-stream"},
    {".gif",    "image/gif"},
    {".gtar",   "application/x-gtar"},
    {".gz", "application/x-gzip"},
    {".h",  "text/plain"},
    {".htm",    "text/html"},
    {".html",   "text/html"},
    {".jar",    "application/java-archive"},
    {".java",   "text/plain"},
    {".jpeg",   "image/jpeg"},
    {".jpg",    "image/jpeg"},
    {".js", "application/x-javascript"},
    {".log",    "text/plain"},
    {".m3u",    "audio/x-mpegurl"},
    {".m4a",    "audio/mp4a-latm"},
    {".m4b",    "audio/mp4a-latm"},
    {".m4p",    "audio/mp4a-latm"},
    {".m4u",    "video/vnd.mpegurl"},
    {".m4v",    "video/x-m4v"},
    {".mov",    "video/quicktime"},
    {".mp2",    "audio/x-mpeg"},
    {".mp3",    "audio/x-mpeg"},
    {".mp4",    "video/mp4"},
    {".mpc",    "application/vnd.mpohun.certificate"},
    {".mpe",    "video/mpeg"},
    {".mpeg",   "video/mpeg"},
    {".mpg",    "video/mpeg"},
    {".mpg4",   "video/mp4"},
    {".mpga",   "audio/mpeg"},
    {".msg",    "application/vnd.ms-outlook"},
    {".ogg",    "audio/ogg"},
    {".pdf",    "application/pdf"},
    {".png",    "image/png"},
    {".pps",    "application/vnd.ms-powerpoint"},
    {".ppt",    "application/vnd.ms-powerpoint"},
    {".pptx",   "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
    {".prop",   "text/plain"},
    {".rc", "text/plain"},
    {".rmvb",   "audio/x-pn-realaudio"},
    {".rtf",    "application/rtf"},
    {".sh", "text/plain"},
    {".tar",    "application/x-tar"},
    {".tgz",    "application/x-compressed"},
    {".txt",    "text/plain"},
    {".wav",    "audio/x-wav"},
    {".wma",    "audio/x-ms-wma"},
    {".wmv",    "audio/x-ms-wmv"},
    {".wps",    "application/vnd.ms-works"},
    {".xml",    "text/plain"},
    {".z",  "application/x-compress"},
    {".zip",    "application/x-zip-compressed"}