亲宝软件园·资讯

展开

android读取assets中Excel android读取assets中Excel表格并显示

ami_daqi 人气:0
想了解android读取assets中Excel表格并显示的相关内容吗,ami_daqi在本文为您仔细讲解android读取assets中Excel的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:android,assets,Excel,下面大家一起来学习吧。

1.在assets下放的excel表格,命名为excel.xls
2.添加读取excel需要的jar包”jxl.jar”,assets是建在main级别目录下,建错地方找不到文件 

 

3.读取excel中的文件

/*获取excel表格中的数据不能在主线程中调用
   xlsName 为表格的名称
   index 表示第几张表格
   */
  public ArrayList<ExcelBean> getExcelData(String xlsName, int index) {
    ArrayList<ExcelBean> list = new ArrayList<>();
    //获取文件管理器
    AssetManager manager = context.getAssets();
    try {
      Workbook workbook = Workbook.getWorkbook(manager.open(xlsName));
      Sheet sheet = workbook.getSheet(index);
      //表格一共有多少行
      int sheetRows = sheet.getRows();
      //将数据添加到集合中
      for (int i = 0; i < sheetRows; i++) {
        ExcelBean bean = new ExcelBean();
        //获取列的数据
        bean.setChinese(sheet.getCell(0, i).getContents());
        bean.setEnglish(sheet.getCell(1, i).getContents());
        bean.setSpell(sheet.getCell(2, i).getContents());
        list.add(bean);
      }
      workbook.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return list;
  }

4.更新UI

public class ExcelDataAsyncTask extends AsyncTask<String, Void, ArrayList<ExcelBean>> {
  private Context context;
  private int index;
  private ExcelData excelData;

  public ExcelDataAsyncTask(Context context, int index, ExcelData excelData) {
    this.context = context;
    this.index = index;
    this.excelData = excelData;
  }

  @Override
  protected ArrayList<ExcelBean> doInBackground(String... params) {
    return getExcelData(params[0], index);
  }

  @Override
  protected void onPostExecute(ArrayList<ExcelBean> excelBeen) {
    super.onPostExecute(excelBeen);
    if (excelBeen != null && excelBeen.size() > 0) {
//      ExcelAdapter adapter=new ExcelAdapter(excelBeen,context);
//      lv.setAdapter(adapter);
      excelData.getData(excelBeen);
    }
  }

/利用接口回调,更新UI
  public interface ExcelData {
    void getData(ArrayList<ExcelBean> list);
  }

Java代码:

 new ExcelDataAsyncTask(ExcelSecondActivity.this, mp3Id, new ExcelDataAsyncTask.ExcelData() {
      @Override
      public void getData(final ArrayList<ExcelBean> list) {
        ExcelAdapter adapter = new ExcelAdapter(list, ExcelSecondActivity.this);
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
          @Override
          public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

             }
        });
      }
    }).execute("excel.xls");

加载全部内容

相关教程
猜你喜欢
用户评论