Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

write a kotlin prog to create excel file in android

To create an Excel file in Android using Kotlin, you can use the Apache POI library.

Here is an example code that demonstrates how to create an Excel file with one sheet, add some
data to it, and save it to the device's storage:

implementation 'org.apache.poi:poi:5.2.0'

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

import android.os.Environment

import org.apache.poi.hssf.usermodel.HSSFWorkbook

import java.io.FileOutputStream

fun createExcelFile() {
// create a new Excel workbook

val workbook = HSSFWorkbook()

// create a new sheet

val sheet = workbook.createSheet("My Sheet")

// add some data to the sheet

val rowData = arrayOf("Name", "Age", "City")

val row = sheet.createRow(0)

for (i in rowData.indices) {

row.createCell(i).setCellValue(rowData[i])

val personData = arrayOf(

arrayOf("John", "30", "New York"),

arrayOf("Mary", "25", "Los Angeles"),

arrayOf("Bob", "40", "Chicago")

for (i in personData.indices) {

val row = sheet.createRow(i + 1)

for (j in personData[i].indices) {

row.createCell(j).setCellValue(personData[i][j])
}

// save the workbook to a file

val file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)

val filePath = "${file.absolutePath}/my_excel_file.xls"

val fileOut = FileOutputStream(filePath)

workbook.write(fileOut)

fileOut.close()

You might also like