在 Android Studio Kotlin 中读取 Excel xlsx 文件数据

问题描述 投票:0回答:1

我是编程新手,需要帮助。

我正在尝试读取 Android studio Kotlin 项目中的 Excel 文件的内容。我计划使用这些数据来备份数据库,但现在,我只是想获取应用程序读取的数据并将其作为日志输出。

我正在使用 Apache POI。

这是我的代码:

private fun importData() {
        // Start the file picker activity
        val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
            addCategory(Intent.CATEGORY_OPENABLE)
            type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" // XLSX-Typ
        }
        importDocumentLauncher.launch(intent)
    }

    private val importDocumentLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == Activity.RESULT_OK) {
                result.data?.data?.let { uri ->
                    lifecycleScope.launch {
                        performImport(uri)
                    }
                }
            }
        }

    private suspend fun performImport(uri: Uri) {
        withContext(Dispatchers.IO) {
            try {
                val factory = DocumentBuilderFactory.newInstance()
                factory.isNamespaceAware = false  // Set to false to disable namespace handling
                val builder = factory.newDocumentBuilder()
                contentResolver.openInputStream(uri)?.use { inputStream ->
                    val document = builder.parse(inputStream)

                    // Add your import logic here based on the document structure
                    val nodeList = document.getElementsByTagName("YourElementName")
                    for (i in 0 until nodeList.length) {
                        val node = nodeList.item(i)
                        val data = node.textContent.trim()
                        // Log the imported data
                        Log.d("ImportActivity", "Imported data: $data")
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                Log.e("ImportActivity", "Error during data import: ${e.message}")
            }
        }
    }

我在 logcat 中收到错误代码:

24727-24727 ViewRootIm...tActivity] com.courier.tiptest                  D  Setup new sync=wmsSync-ViewRootImpl@787e21e[ExportActivity]#8
2024-01-08 05:44:28.023 24727-24727 ViewRootIm...tActivity] com.courier.tiptest                  D  Creating new active sync group ViewRootImpl@787e21e[ExportActivity]#9
2024-01-08 05:44:28.023 24727-24727 ViewRootIm...tActivity] com.courier.tiptest                  D  registerCallbacksForSync syncBuffer=false
2024-01-08 05:44:28.034 24727-24818 System.err              com.courier.tiptest                  W  org.xml.sax.SAXParseException: Unexpected token (position:TEXT PK????B.'X????...@1:134 in java.io.InputStreamReader@6306f26) 
2024-01-08 05:44:28.034 24727-24818 System.err              com.courier.tiptest                  W      at org.apache.harmony.xml.parsers.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:147)
2024-01-08 05:44:28.035 24727-24818 System.err              com.courier.tiptest                  W      at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:107)
2024-01-08 05:44:28.035 24727-24818 System.err              com.courier.tiptest                  W      at com.courier.tiptest.ui.statistic.ExportActivity$performImport$2.invokeSuspend(ExportActivity.kt:221)
2024-01-08 05:44:28.035 24727-24818 System.err              com.courier.tiptest                  W      at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
2024-01-08 05:44:28.035 24727-24818 System.err              com.courier.tiptest                  W      at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:108)
2024-01-08 05:44:28.035 24727-24818 System.err              com.courier.tiptest                  W      at kotlinx.coroutines.internal.LimitedDispatcher$Worker.run(LimitedDispatcher.kt:115)
2024-01-08 05:44:28.035 24727-24818 System.err              com.courier.tiptest                  W      at kotlinx.coroutines.scheduling.TaskImpl.run(Tasks.kt:103)
2024-01-08 05:44:28.035 24727-24818 System.err              com.courier.tiptest                  W      at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:584)
2024-01-08 05:44:28.035 24727-24818 System.err              com.courier.tiptest                  W      at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:793)
2024-01-08 05:44:28.035 24727-24818 System.err              com.courier.tiptest                  W      at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:697)
2024-01-08 05:44:28.035 24727-24787 ViewRootIm...tActivity] com.courier.tiptest                  D  Received frameDrawingCallback syncResult=0 frameNum=1.
2024-01-08 05:44:28.035 24727-24818 System.err              com.courier.tiptest                  W      at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:684)
2024-01-08 05:44:28.035 24727-24818 ImportActivity          com.courier.tiptest                  E  Error during data import: Unexpected token (position:TEXT PK????B.'X????...@1:134 in java.io.InputStreamReader@6306f26) 
2024-01-08 05:44:28.036 24727-24787 ViewRootIm...tActivity] com.courier.tiptest                  I  mWNT: t=0xb40000734470e750 mBlastBufferQueue=0xb4000073046f4050 fn= 1 caller= android.view.ViewRootImpl$8.onFrameDraw:13614 android.view.ThreadedRenderer$1.onFrameDraw:788 <bottom of call stack> 
2024-01-08 05:44:28.036 24727-24787 ViewRootIm...tActivity] com.courier.tiptest                  D  Setting up sync and frameCommitCallback

我尝试询问 ChatGPT,但它只给了我各种不同的错误并且没有解决方案。

android excel kotlin xlsx
1个回答
0
投票

要读取 XLSX-Typ 文件,请检查以下解决方案 我正在使用 apac poi 读取文件

build.gradle

dependencies {
implementation 'org.apache.poi:poi:5.2.2'
implementation 'org.apache.poi:poi-ooxml:5.2.2'
}

创建文件选择意图:

Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("application/vnd.ms-excel");
startActivityForResult(intent, FILE_SELECT_CODE);

处理文件选择结果:

 @Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == FILE_SELECT_CODE && resultCode == RESULT_OK) {
        Uri uri = data.getData();
        readExcelFile(uri);
    }
}

从 URI 读取 Excel 文件:

private void readExcelFile(Uri uri) {
    try {
        InputStream inputStream = getContentResolver().openInputStream(uri);
        Workbook workbook = WorkbookFactory.create(inputStream);
        Sheet sheet = workbook.getSheetAt(0); // Assuming you want the first sheet

        // Iterate through rows and cells
        Iterator<Row> rowIterator = sheet.iterator();
        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            Iterator<Cell> cellIterator = row.cellIterator();
            while (cellIterator.hasNext()) {
                Cell cell = cellIterator.next();
                switch (cell.getCellType()) {
                    case STRING:
                        String cellValue = cell.getStringCellValue();
                        // Do something with the string value
                        break;
                    case NUMERIC:
                        double numericCellValue = cell.getNumericCellValue();
                        // Do something with the numeric value
                        break;
                    // Handle other cell types as needed
                }
            }
        }
        workbook.close();
    } catch (IOException | InvalidFormatException e) {
        e.printStackTrace();
    }
}

我希望这对你有用

© www.soinside.com 2019 - 2024. All rights reserved.