Create XL sheet using kotlin and poi in android


Create XL Sheet using Kotlin and Apache POI library in an Android application follow below steps: 


1. Create new Android application using Android studio

2. Add the dependencies for Apache POI in your project's build. Gradle file. Trying to add latest library 

3. Add write permission for save xl file in storage of android device.

4. I use the XSSFWorkbook class from the POI library to create a new workbook and create a sheet within it.

Code Example:

val myWorkBook = XSSFWorkbook()
val sheet: Sheet = myWorkBook.createSheet("FirstSeetExample")

5. I also add header  style  of sheet example below:

         val headerFont: Font = myWorkBook.createFont()
         headerFont.color= IndexedColors.BLUE.index
         val cellStyle = sheet.workbook.createCellStyle()
         cellStyle.fillForegroundColor = IndexedColors.RED.getIndex()
         cellStyle.setFont(headerFont)

6. Create model class for data and add data to model class:


  xldataList.add(XlData("Employee Id","Name","Department","Salary"))
        xldataList.add(XlData("10001","Test Name1","Clark","10000"))
        xldataList.add(XlData("10002","Test Name2","Clark","20000"))

7. Create a header row in the sheet and populate it with column names or headers.

  val row: Row =sheet.createRow(rowNum++)


8. Add data rows to the sheet by iterating over your data and populating each cell in the row with the corresponding values.


9. Save the workbook to a file using a FileOutputStream. Provide the desired file path and name.

 

val excelFile = File(ourAppFileDirectory, current+"test.xlsx")
         
        //Write a workbook to the file using a file outputstream
 
        var xlwrite=false
 
        try {
 
            val fileOut = FileOutputStream(excelFile)
 
            ourWorkbook.write(fileOut)
 
            fileOut.close()
 
            xlwrite=true
 
        } catch (e: FileNotFoundException) {
 
            xlwrite=false
 
            e.printStackTrace()
 
        } catch (e: IOException) {
 
            xlwrite=false
 
            e.printStackTrace()
 
        }finally {
 
            if(xlwrite){
 
                binding.tvResult.text="Xl File Create Successfully please check path "+excelFile.absolutePath
 
            }else{
 
                binding.tvResult.text="Xl File Create failure  "            }



Close the workbook and handle any exceptions that may occur during file operations. that's it .:https://github.com/nipamaity/XlSheetCreate/tree/master


Comments

Popular posts from this blog

Adding Multilingual Support in Kotlin Android Apps

The Dhari Devi Temple