Shobhith
Shobhith

Reputation: 505

How Display XLSX Files in Android

I have a xlsx file in my android assets folder. I need to display the xlsx in android. How to load and display xlsx from local assets folder.

Approach tried so far using webview:

val excelFilePath = "file:///android_asset/asmls.xlsx"

loadUrl(excelFilePath)

When I went through multiple sites, It is mentioned that xlsx is not directly supported by Android Webview. Is there any work around or alternative libraries available for the same purpose?

Upvotes: 1

Views: 1377

Answers (2)

Bashu
Bashu

Reputation: 1761

  1. Using Intents to Launch External Apps by prompting the user to choose a suitable app:

fun openExcelFile(con: Context, file: File) {
    val uri = FileProvider.getUriForFile(con, "${con.packageName}.provider", file)
    val intent = Intent(Intent.ACTION_VIEW).apply {
        setDataAndType(uri, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
        addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) // Required for FileProvider
    }
    try {
        con.startActivity(intent)
    } catch (e: ActivityNotFoundException) {
        Toast.makeText(con, "No app found to open Excel file", Toast.LENGTH_SHORT).show()
    }
}

  1. You can use below lib ->

implementation("org.apache.poi:poi:5.2.5")

FileInputStream inputStream = new FileInputStream("file:////path/to/your/file.xlsx");
Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0); // Access the first sheet

// Iterate through rows and cells:
for (Row row : sheet) {
    for (Cell cell : row) {
        // Process cell data based on cell type (string, numeric, etc.)
    }
}

workbook.close();

Upvotes: 0

LethalMaus
LethalMaus

Reputation: 956

Avoiding direct display of XLSX files within your app is advisable for compatibility and performance reasons. Opt for a smoother user experience by utilizing an intent chooser with the appropriate MIME type. This enables users to seamlessly open the file using their preferred external app.

val file = "file:///android_asset/asmls.xlsx"
val uri = Uri.parse(file)

val intent = Intent(Intent.ACTION_VIEW)
intent.setDataAndType(uri, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")

try {
    startActivity(Intent.createChooser(intent, "Choose an app to open the XLSX file"))
} catch (e: ActivityNotFoundException) {
    //handle no apps found eg inform the user
}

Double check the MIME type and it could be that you need to set android:usesCleartextTraffic to true

Upvotes: 1

Related Questions