android 打开路径,android打开指定路径的word或excel文件进行读取

最近小弟的项目中有需要读取word与excel的模块,研究了一下,把心得分享给大家.

e3ea907629fd

QQ图片20180413135257.jpg

首先是布局文件

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:orientation="horizontal">

android:id="@+id/et_url"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_weight="1"

android:hint="请选择或输入文件路径"/>

android:id="@+id/bt_url"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="选择路径"/>

android:id="@+id/bt_open"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="打开文件"/>

activity代码:

/*输入路径*/

etUrl = (EditText) findViewById(R.id.et_url);

/*自己选择路径*/

btUrl = (Button) findViewById(R.id.bt_url);

/*打开文件*/

btOpen = (Button) findViewById(R.id.bt_open);

btUrl.setOnClickListener(this);

btOpen.setOnClickListener(this);

/*选择文件路径*/

case R.id.bt_url:

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);

intent.setType("*/*");//设置类型,我这里是任意类型,任意后缀的可以这样写。

intent.addCategory(Intent.CATEGORY_OPENABLE);

startActivityForResult(intent, 1);

break;

/*打开文件*/

case R.id.bt_open:

if (fileUrl!= null) {

try {

File file = new File(fileUrl);

Intent intent2 = new Intent("android.intent.action.VIEW");

intent2.addCategory("android.intent.category.DEFAULT");

intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

Uri uri = Uri.fromFile(file);

//application/msword

//application/vnd.ms-excel

if (fileUrl.contains(".docx")){

intent2.setDataAndType(uri, "application/msword");

}else if (fileUrl.contains(".xlsx")){

intent2.setDataAndType(uri, "application/vnd.ms-excel");

}else {

intent2.setDataAndType(uri, "text/plain");

}

startActivity(intent2);

} catch (Exception e) {

//没有安装第三方的软件会提示

Toast toast = Toast.makeText(DayweekManagerActivity.this, "没有找到打开该文件的应用程序", Toast.LENGTH_SHORT);

toast.show();

}

// Intent intent2 = new Intent();

// intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

// intent2.setAction(Intent.ACTION_VIEW);

// intent2.setDataAndType((Uri) etUrl.getText(), "text/plain");

// startActivity(intent2);

} else {

Toast.makeText(this, "请选择或输入文件路径", Toast.LENGTH_SHORT).show();

return;

}

break;

/*接收到刚才选择的文件路径*/

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

if (resultCode == Activity.RESULT_OK) {

if (requestCode == 1) {

Uri uri = data.getData();

etUrl.setText(uri.getPath().toString());

fileUrl = etUrl.getText().toString();

}

}

}

好了,代码到这里就结束了,喜欢就给个赞吧!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值