Android手机上利用jxl.jar包对sd卡上的表格实现增删改查、导入导出功能

前言

最近在android手机端接触有关使用jxl.jar包操纵表格导入导出的东西,遇见了很多问题,也有不少收获,特意写了一个demo通过这篇博客来记录一下。

项目结构如上左图,首先需要下载jxl.jar。添加到项目libs文件夹下,然后右键点击add as library将其导入到项目。新建了一个User类用于测试,该类只有三个String变量name、sex、age,分别表示姓名、性别、年龄。MainActivity界面只有四个按钮分别对应数据的增删改查,如上右图。因为涉及到对sd卡的读写,需要添加权限。

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

如果你的手机android系统为6.0以上,还需要动态申请权限,因为对sd读写属于敏感权限。我这里就不演示如何申请了了,因为我的测试环境小于6.0。

jxl.jar的下载地址:https://pan.baidu.com/s/15GV9JdGNO8ENb82wJNP1rA

项目的下载地址:https://github.com/gumaoqi/MyExcelTest

user.java


public class User {
    String name;
    String sex;
    String age;

    public User(String name, String sex, String age) {
        this.name = name;
        this.sex = sex;
        this.age = age;
    }

    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 getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
}

没什么好说的,用户类。

activity.main_xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/add_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="5dp"
        android:text="添加" />

    <Button
        android:id="@+id/delete_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="5dp"
        android:text="删除" />

    <Button
        android:id="@+id/update_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="5dp"
        android:text="修改" />

    <Button
        android:id="@+id/query_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="5dp"
        android:text="查询" />
</LinearLayout>

也没有什么好说的,界面包含了四个按钮

MainActivity.java


public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    final String TAG = "MainActivity";
    Button addButton;
    Button deleteButton;
    Button updateButton;
    Button queryButton;

    File file;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        addButton = findViewById(R.id.add_button);
        deleteButton = findViewById(R.id.delete_button);
        updateButton = findViewById(R.id.update_button);
        queryButton = findViewById(R.id.query_button);
        addButton.setOnClickListener(this);
        deleteButton.setOnClickListener(this);
        updateButton.setOnClickListener(this);
        queryButton.setOnClickListener(this);

        file = new File(Environment.getExternalStorageDirectory().getPath() + "/aaaExcelTest");//创建文件夹
        if (!file.exists()) {
            file.mkdir();
        }
        file = new File(Environment.getExternalStorageDirectory().getPath() + "/aaaExcelTest/user.xls");//指明存放数据的excel表示
        if (!file.exists()) {//如果文件不存在,创建文件
            createFile(file);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.add_button:
                User user = new User("用户" + System.currentTimeMillis(), "男", new Random().nextInt(20) + 20 + "");
                addUser(user, file);
                break;
            case R.id.delete_button:
                deleteUser(file);
                break;
            case R.id.update_button:
                updateUser(file);
                break;
            case R.id.query_button:
                queryUser(file);
                break;
        }
    }

    private void createFile(File file) {//创建一个file,并将第一行前三列分别设为:姓名,性别,年龄
        OutputStream os = null;
        WritableWorkbook wwb = null;
        try {
            file.createNewFile();
            os = new FileOutputStream(file);
            //创建一个可写的Workbook
            wwb = Workbook.createWorkbook(os);

            //创建一个可写的sheet,第一个参数是名字,第二个参数是第几个sheet,写入第一行
            WritableSheet sheet = wwb.createSheet("第一个sheet", 0);
            //创建一个Label,第一个参数是x轴,第二个参数是y轴,第三个参数是内容,第四个参数可选,指定类型
            Label label1 = new Label(0, 0, "姓名");
            Label label2 = new Label(1, 0, "性别");
            Label label3 = new Label(2, 0, "年龄");

            //把label加入sheet对象中
            sheet.addCell(label1);
            sheet.addCell(label2);
            sheet.addCell(label3);
            wwb.write();
            //只有执行close时才会写入到文件中,可能在close方法中执行了io操作
            wwb.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {//关闭流
            try {
                if (os != null) {
                    os.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void addUser(User user, File file) {
        Workbook originWwb = null;
        WritableWorkbook newWwb = null;
        try {
            //插入数据需要拿到原来的表格originWwb,然后通过其创建一个新的表格newWwb,在newWwb上完成插入操作
            originWwb = Workbook.getWorkbook(file);
            newWwb = Workbook.createWorkbook(file, originWwb);
            //获取指定索引的表格
            WritableSheet ws = newWwb.getSheet(0);
            // 获取该表格现有的行数,将数据插入到底部
            int row = ws.getRows();
            Label lab1 = new Label(0, row, user.getName());//参数分别代表:列数,行数,插入的内容
            Label lab2 = new Label(1, row, user.getSex());
            Label lab3 = new Label(2, row, user.getAge());
            ws.addCell(lab1);
            ws.addCell(lab2);
            ws.addCell(lab3);
            // 从内存中的数据写入到sd卡excel文件中。
            newWwb.write();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {//释放资源
            if (originWwb != null) {
                originWwb.close();
            }
            if (newWwb != null) {
                try {
                    newWwb.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void deleteUser(File file) {
        Workbook originWwb = null;
        WritableWorkbook newWwb = null;
        try {
            //插入数据需要拿到原来的表格originWwb,然后通过其创建一个新的表格newWwb,在newWwb上完成插入操作
            originWwb = Workbook.getWorkbook(file);
            newWwb = Workbook.createWorkbook(file, originWwb);
            //获取指定索引的表格
            WritableSheet ws = newWwb.getSheet(0);
            // 获取该表格现有的行数,将数据插入到底部
            int row = ws.getRows();
            ws.removeRow(row - 1);
            // 从内存中的数据写入到sd卡excel文件中。
            newWwb.write();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {//释放资源
            if (originWwb != null) {
                originWwb.close();
            }
            if (newWwb != null) {
                try {
                    newWwb.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void updateUser(File file) {
        Workbook originWwb = null;
        WritableWorkbook newWwb = null;
        try {
            //插入数据需要拿到原来的表格originWwb,然后通过其创建一个新的表格newWwb,在newWwb上完成插入操作
            originWwb = Workbook.getWorkbook(file);
            newWwb = Workbook.createWorkbook(file, originWwb);
            //获取指定索引的表格
            WritableSheet ws = newWwb.getSheet(0);
            // 获取该表格现有的行数,将数据插入到底部
            int row = ws.getRows();
            ws.removeRow(row - 1);
            Label lab1 = new Label(0, row - 1, "张三");//参数分别代表:列数,行数,插入的内容
            Label lab2 = new Label(1, row - 1, "女");
            Label lab3 = new Label(2, row - 1, "60");
            ws.addCell(lab1);
            ws.addCell(lab2);
            ws.addCell(lab3);
            // 从内存中的数据写入到sd卡excel文件中。
            newWwb.write();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {//释放资源
            if (originWwb != null) {
                originWwb.close();
            }
            if (newWwb != null) {
                try {
                    newWwb.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void queryUser(File file) {
        InputStream is = null;
        Workbook workbook = null;
        try {
            is = new FileInputStream(file.getPath());//获取流
            workbook = Workbook.getWorkbook(is);
            Sheet sheet = workbook.getSheet(0);
            for (int i = 0; i < sheet.getRows(); i++) {
                Log.i(TAG, sheet.getCell(0, i).getContents() + "-" + sheet.getCell(1, i).getContents() +
                        "-" + sheet.getCell(2, i).getContents());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (workbook != null) {
                workbook.close();
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

 

createFile方法:创建一个user.xls表格,并设置其第一行,分别为姓名,性别,年龄,在oncreate中会判断该表格是否存在,如果不存在则调用该方法。创建后的表格文件内容如下图所示:

addUser方法:添加一个用户,下面是一些重要代码。

int row = ws.getRows();//获取当前的行数
Label lab1 = new Label(0, row, user.getName());//参数分别代表:列数,行数,插入的内容,将用户的名字插入到下一行的第一列。

点击三个添加按钮,插入了三个用户如下图:

updateUser方法:更新user表格

delete方User方法:删除表格的最后一行。重要代码:

int row = ws.getRows();
ws.removeRow(row - 1);

获取当前行数,然后删除这一行

点击update后,表格变为下图,删除功能结果请自行查看。

QueryUser方法:查询表格的所有内容,然后输出到控制台,重要代码

is = new FileInputStream(file.getPath());//获取流
workbook = Workbook.getWorkbook(is);
Sheet sheet = workbook.getSheet(0);//获取表格对象
for (int i = 0; i < sheet.getRows(); i++) {
    Log.i(TAG, sheet.getCell(0, i).getContents() + "-" + sheet.getCell(1, i).getContents() +
            "-" + sheet.getCell(2, i).getContents());
}

至此,已成功利用jxl.jar对表格实现了增删改查的功能。操作的表格在sd卡根目录的aaaExcelTest文件夹下。

博主水平有限,如有指正错误和其他建议请在评论区留言。

后记

在createfile方法中,如果将wwb.close();放在finally中是释放,会发生异常,暂时不知道其原因,捕捉异常后网上去查询也没有类似的信息,后续可以尝试查看一下源码。

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值