1.Activity中代码
package com.me.mydemos.ui.activity.excel;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import com.me.mydemos.base.BaseActivity;
import com.me.mydemos.databinding.ActivityExcelImportExportBinding;
import com.me.mydemos.ui.excel.SheetHelper;
import com.me.mydemos.util.FileUtils2;
import com.me.mydemos.util.LogUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;
import java.util.ArrayList;
import java.util.List;
public class ExcelImportExportActivity extends BaseActivity {
public static final String DOC = "application/msword";
public static final String DOCX = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
public static final String XLS = "application/vnd.ms-excel application/x-excel";
public static final String XLSX = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
public static final String PPT = "application/vnd.ms-powerpoint";
public static final String PPTX = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
public static final String PDF = "application/pdf";
@Override
protected int getLayoutId() {
return 0;
}
@Override
protected void init() {
//导出
binding.tvExport.setOnClickListener(v -> {
initPermission();
});
//导入
binding.tvImport.setOnClickListener(v -> {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// intent.setType("*/*");//设置类型,我这里是任意类型,任意后缀的可以这样写。
intent.setType(XLS + "|" + XLSX);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, 1000);
});
}
private boolean havePermission = false;
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
private AlertDialog dialog;
private void checkPermission() {
// 检查权限(NEED_PERMISSION)是否被授权 PackageManager.PERMISSION_GRANTED表示同意授权
if (Build.VERSION.SDK_INT >= 30) {
if (!Environment.isExternalStorageManager()) {
if (dialog != null) {
dialog.dismiss();
dialog = null;
}
dialog = new AlertDialog.Builder(this)
.setTitle("提示")//设置标题
.setMessage("请开启文件访问权限,否则无法正常使用本应用!")
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
dialog.dismiss();
}
})
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
// Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
// startActivity(intent);
}
}).create();
dialog.show();
} else {
havePermission = true;
Log.i("swyLog", "Android 11以上,当前已有权限");
initPermission();
}
} else {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//申请权限
if (dialog != null) {
dialog.dismiss();
dialog = null;
}
dialog = new AlertDialog.Builder(this)
.setTitle("提示")//设置标题
.setMessage("请开启文件访问权限,否则无法正常使用本应用!")
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
ActivityCompat.requestPermissions(ExcelImportExportActivity.this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
}
}).create();
dialog.show();
} else {
havePermission = true;
Log.i("swyLog", "Android 6.0以上,11以下,当前已有权限");
}
} else {
havePermission = true;
Log.i("swyLog", "Android 6.0以下,已获取权限");
}
}
}
private String[] getReadWritePermissions() {
// LogUtil.d("Build.VERSION.SDK_INT:" + Build.VERSION.SDK_INT);
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
// return new String[]{
// android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
// android.Manifest.permission.READ_MEDIA_IMAGES,
// android.Manifest.permission.READ_MEDIA_AUDIO,
// android.Manifest.permission.READ_MEDIA_VIDEO
// };
// } else {
return new String[]{
android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
android.Manifest.permission.READ_EXTERNAL_STORAGE
};
// }
}
@SuppressLint("CheckResult")
private void initPermission() {
RxPermissions permissions = new RxPermissions(this);
permissions.request(
android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
android.Manifest.permission.READ_EXTERNAL_STORAGE
).subscribe(result -> {
if (result) {
new Thread(new Runnable() {
@Override
public void run() {
List deviceInfos = new ArrayList<>();
for (int i = 0; i < 20; i++) {
SheetHelper.DeviceInfo deviceInfo = new SheetHelper.DeviceInfo();
deviceInfo.setRow(String.valueOf(i + 1));//序号
deviceInfo.setDeviceId("1531359236" + i);//设备id
deviceInfo.setPhoneBrand("华为" + i);//手机品牌
deviceInfo.setLatestLocation("北京" + i);//最新位置
deviceInfo.setChangeSum(String.valueOf(i));//换机换卡次数
deviceInfo.setInstallAppSum(String.valueOf(i));//应用安装数量
deviceInfo.setUninstallAppSum(String.valueOf(i));//卸载应用次数
deviceInfo.setViolationAppSum(String.valueOf(i));//违规app个数
deviceInfos.add(deviceInfo);
}
String[] title = {"序号", "设备号", "手机品牌", "最新位置", "换机换卡次数", "应用安装数量", "卸载应用次数", "违规app个数"};
boolean isSuccess = SheetHelper.exportExcel(title, deviceInfos, "exportExcel", "导出测试", ExcelImportExportActivity.this, true);
runOnUiThread(() -> {
if (isSuccess) {
Toast.makeText(ExcelImportExportActivity.this, "导出成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ExcelImportExportActivity.this, "导出失败", Toast.LENGTH_SHORT).show();
}
});
}
}).start();
} else {
Toast.makeText(context, "请授予应用读写的权限", Toast.LENGTH_SHORT).show();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (resultCode == Activity.RESULT_OK && requestCode == 1000) {
Uri uri = data.getData();//得到uri,后面就是将uri转化成file的过程。
LogUtil.d("uri:" + uri.getPath());
String absolutePath = FileUtils2.getUriPath(this, uri);
Log.d("选择了文件", "文件路径:" + absolutePath);
new Thread(new Runnable() {
@Override
public void run() {
List strings = SheetHelper.readExcel(absolutePath);
runOnUiThread(new Runnable() {
@Override
public void run() {
if (strings != null) {
String str = "";
for (String string : strings) {
String[] split = string.split("&&");
for (String s : split) {
Log.i("拿到数据", s);
str += s;
}
str += "\n";
}
LogUtil.d("数据:" + str);
Toast.makeText(context, "导入成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "导入失败", Toast.LENGTH_SHORT).show();
}
}
});
}
}).start();
}
} catch (Exception e) {
Toast.makeText(context, "导入异常", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_EXTERNAL_STORAGE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
havePermission = true;
Toast.makeText(this, "授权成功!", Toast.LENGTH_SHORT).show();
initPermission();
} else {
havePermission = false;
Toast.makeText(this, "授权被拒绝!", Toast.LENGTH_SHORT).show();
}
}
}
}
}
2、AndroidManifest.xml
3、res/xml/file_paths.xml