android读取excel数据的方法

要有sd卡读取写入权限。

    package="com.mytest.readexcell" >

   

   

   

   

   

   

    //以上两个是文件写读权限声明。

   

        ……

一种是excel文件放在assets文件夹内,比如 test.xls

注意,assets和java文件夹在同一个目录下,

android读取excel数据的方法_第1张图片
图片发自App

    public void readExcel(int i,int y) {

        try {

            TextView danxuan=(TextView)findViewById(R.id.danxuantimu);

        AssetManager assetManager=getAssets();

            Workbook book = Workbook.getWorkbook(assetManager.open("test.xls"));

            Sheet sheet = book.getSheet(0);

            id.setText(i+".");

            danxuan.setText(sheet.getCell(2,y).getContents());

            book.close();

        } catch (Exception e) {

  TextView etxt= (TextView)findViewById(R.id.etx);

            etxt.setText(e.toString());

        }

    }

另一种 是通过文件的地址来获取。地址的方式有两种:⒈是不可更改的,在代码内写好的,只能通过文件管理器来复制文件到指定的目录下。⒉是通过程序内调用文件管理器来选择指定文件。选定后把文件的地址传递给代码。也可以通过复制到指定目录下。

public void readExcel() {

        try {

            txt.setText("运行readexcel");

            txtt.setText("初始态");

          //InputStream iss = new FileInputStream("/storage/emulated/0/test.xls");

            AssetManager assetManager=getAssets();

            //不需要加“assets”,注意!!

         

            Workbook book = Workbook.getWorkbook(assetManager.open("/storage/emulated/0/test.xls"));

        //以上是文件的绝对地址。

            int num = book.getNumberOfSheets();

            txt.setText("the num of sheets is " + num+ "\n");

            // 获得第一个工作表对象

            Sheet sheet = book.getSheet(0);

            int Rows = sheet.getRows();

            int Cols = sheet.getColumns();

            txt.append("the name of sheet is " + sheet.getName() + "\n");

            txt.append("total rows is " + Rows + "\n");

            txt.append("total cols is " + Cols + "\n");

            for (int i = 0; i < Cols; ++i) {

                for (int j = 0; j < Rows; ++j) {

                    // getCell(Col,Row)获得单元格的值

                    txt.append("contents:" + sheet.getCell(i,j).getContents() + "\n");

                }

            }

            book.close();

        } catch (Exception e) {

            //System.out.println(e);

          TextView etxt= (TextView)findViewById(R.id.etx);

          etxt.setText(e.toString());

           

           

        }

    }

   

以上两种经不起压力测试,容易造成内存溢出。用流的方式读取文件比较好。

你可能感兴趣的:(android读取excel数据的方法)