天天看點

Android Excel(xls,xlsx)表格資料簡單生成和讀取嘗試

1.我們資料一般常用的有SharedPreferences以鍵值對資料形式儲存到本地xml裡面,對于一些大量字段的資料,就不能直覺看到資料了。

Android Excel(xls,xlsx)表格資料簡單生成和讀取嘗試

                -- 我們也可以根據自己的需求,使用适合自己的版本的表格

2.添加jxl.jar包,導入到自己項目

連結:https://pan.baidu.com/s/1QSIwXDHVrfasW9pWbHzAaQ 

提取碼:051l 

複制這段内容後打開百度網盤手機App,操作更友善哦

3.自己定義資料類:

package com.example.test_01.excel;

public class Userinfo {
    private int id;
    private String name;
    private String sex;
    private String phone;
    private String email;

    public Userinfo() {
    }

    public Userinfo(int id, String name, String sex, String phone, String email) {
        this.id = id;
        this.name = name;
        this.sex = sex;
        this.phone = phone;
        this.email = email;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", phone='" + phone + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}
           

4.把資料導進去excel表格:

private static final String TAG = "ExcelActivity";
 private String excel_save;
 private List<Userinfo> list;
           
excel_save = getApplication().getExternalCacheDir() + File.separator + "TestExcel";
       //新增三個使用者資訊
       list=new ArrayList<>();
       list.add(new Userinfo(1,"小明","男","18123456789","[email protected]"));
       list.add(new Userinfo(2,"小花","女","18123456789","[email protected]"));
       list.add(new Userinfo(3,"小南","男","18123456789","[email protected]"));
       Log.i(TAG, "onCreate: list="+list.toString());
           

調用init_SaveExcel(),把資料儲存 

/**
     * 增加Excel儲存資料
     */
    private void init_SaveExcel() {

        // 準備設定excel工作表的标題
        String[] title = {"id", "name", "sex", "phone", "email"};

        File BuildDir = new File(getApplication().getExternalCacheDir(), "TestExcel");   //打開UHFData目錄,如不存在則生成
        if (BuildDir.exists() == false) BuildDir.mkdirs();

        // 建立Excel工作薄
        WritableWorkbook wwb;
        // 在SD卡中,建立立一個jxl檔案,并寫入資料
        try {
            wwb = Workbook.createWorkbook(new File(excel_save + File.separator + "userinfo.xls"));
            Log.i(TAG, "init_veinSaveExcel: 建立檔案成功!");
            // 添加第一個工作表并設定第一個Sheet的名字
            WritableSheet sheet = wwb.createSheet("UserData", 0);
            Label label;

            for (int i = 0; i < title.length; i++) {
                label = new Label(i, 0, title[i]);
                // 将定義好的單元格添加到工作表中
                try {
                    sheet.addCell(label);
                } catch (WriteException e) {
                    e.printStackTrace();
                }
            }
            //查找測試的資料
            if (list.isEmpty()) {
                Log.i(TAG, "init_veinExcel: ls_user 資料為null");
            } else {
                Log.i(TAG, "init_veinExcel: ls_user 資料不為null" + list.toString());

                for (int i = 0; i < list.size(); i++) {
                    /*
                     * 儲存數字到單元格,需要使用jxl.write.Number 必須使用其完整路徑,否則會出現錯誤
                     */
                    //添加使用者id
                    label = new Label(0, i + 1, String.valueOf(list.get(i).getId()));
                    sheet.addCell(label);
                    //添加使用者名
                    label = new Label(1, i + 1, list.get(i).getName());
                    sheet.addCell(label);
                    //添加性别
                    label = new Label(2, i + 1, list.get(i).getSex());
                    sheet.addCell(label);
                    //添加電話
                    label = new Label(3, i + 1, list.get(i).getPhone());
                    sheet.addCell(label);
                    //添加郵箱
                    label = new Label(4, i + 1, list.get(i).getEmail());
                    sheet.addCell(label);
                }
            }
            wwb.write(); //寫入資料
            wwb.close(); //關閉檔案


        } catch (IOException e) {
            e.printStackTrace();
        } catch (RowsExceededException e) {
            e.printStackTrace();
        } catch (WriteException e) {
            e.printStackTrace();
        }
    }
           

 最終生成表格儲存

Android Excel(xls,xlsx)表格資料簡單生成和讀取嘗試

我這邊沒有軟體打不開,直接把檔案複制到電腦打開

Android Excel(xls,xlsx)表格資料簡單生成和讀取嘗試

打開excel表

Android Excel(xls,xlsx)表格資料簡單生成和讀取嘗試

5.讀取excel資料:

private void init_ReadExcel() {
        String id = null, name = null, sex = null, phone = null, email = null;
        Workbook book = null;
        try {
            book = Workbook.getWorkbook(new File(excel_save + File.separator + "userinfo.xls"));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (BiffException e) {
            e.printStackTrace();
        }

        //獲得第一個工作表對象
        Sheet sheet = book.getSheet("UserData");

        int rows = sheet.getRows();
        int cols = sheet.getColumns();

        System.out.println("總列數:" + cols);
        System.out.println("總行數:" + rows);
        System.out.println("----------------------------");

        //循環讀取資料
        for (int j = 1; j < rows; j++) {

            for (int i = 0; i < cols; i++) {
                System.out.println("第" + j + "行,第" + i + "列為:" + sheet.getCell(i, j).getContents());
                //如果使用者名和使用者組好相同,則不插入,否則就插入
                switch (i) {
                    case 0:
                        id = sheet.getCell(i, j).getContents();
                        break;
                    case 1:
                        name = sheet.getCell(i, j).getContents();
                        break;
                    case 2:
                        sex = sheet.getCell(i, j).getContents();
                        break;
                    case 3:
                        phone = sheet.getCell(i, j).getContents();
                        break;
                    case 4:
                        email = sheet.getCell(i, j).getContents();
                        break;
                    default:
                        Log.i(TAG, "init_veinReadExcel: 未知參數!");
                        break;
                }
            }

            Log.i(TAG, "Excel:第" + j + "條資訊={" + "id=" + id + ",name=" + name + ",sex=" + sex + ",phone=" + phone + ",email=" + email + "}");

        }
    }

           

看輸出結果

Android Excel(xls,xlsx)表格資料簡單生成和讀取嘗試

 到這裡基本是建立資料表格和讀取指定表格的資料,就實作了,就可以把這些資料單獨分離出來,結合自己的需求來實作自己的功能啦!如果文章有問題,可以評論留言,修改不足和交流學習!