BÀI 64 - LƯU DỮ LIỆU THÀNH FILE EXCEL TRONG ANDROID
Thêm thư viện sau:
implementation 'org.apache.poi:poi:3.17'
Thêm quyền đọc và ghi vào bộ nhớ điện thoại:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
tools:ignore="ScopedStorage" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Bây giờ code như sau:
File filePath = new File(Environment.getExternalStorageDirectory() + "/Demo.xls");
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
catchImageviewExcel();
}
private void catchImageviewExcel() {
imgExcel.setOnClickListener(v -> ActivityCompat.requestPermissions(getActivity()
, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE
, Manifest.permission.READ_EXTERNAL_STORAGE}
, PackageManager.PERMISSION_GRANTED));
CreateFileExcel();
}
private void CreateFileExcel() {
HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
HSSFSheet hssfSheet = hssfWorkbook.createSheet();
HSSFRow hssfRow = hssfSheet.createRow(0);
HSSFCell hssfCell = hssfRow.createCell(0);
hssfCell.setCellValue("Susscessful"); // In giá trị tại (0, 0) là Sussecceful
try {
if (!filePath.exists()) {
filePath.createNewFile();
}
FileOutputStream fileOutputStream = new FileOutputStream(filePath);
hssfWorkbook.write(fileOutputStream);
if (fileOutputStream != null) {
fileOutputStream.flush();
fileOutputStream.close();
}
Log.e("excel", String.valueOf(filePath));
} catch (Exception e) {
e.printStackTrace();
}
}
File excel này được lưu ở bộ nhớ ngoài của thiết bị. Có thể trong thẻ sd hoặc trong thư mục tài liệu của bộ nhớ trong