Working with Excel in Kotlin: Apache POI and Wrapper Libraries
Kotlin, as a modern programming language for the JVM, provides excellent capabilities for working with tabular data. Although the Kotlin ecosystem has no native support for the .xlsx format, you can use proven Java libraries adapted to Kotlin syntax. In this article, we will look at the main tool — Apache POI — and two popular Kotlin wrappers: poi-kotlin and kotlinpoi.
1. Apache POI — the foundation for working with Excel
Apache POI is a mature Java library for reading and writing Microsoft Office format files (OLE2 and OOXML). For working with modern .xlsx files, the poi-ooxml submodule is used. Add the dependency to build.gradle.kts:
dependencies { implementation("org.apache.poi:poi:5.3.0") implementation("org.apache.poi:poi-ooxml:5.3.0")}Reading an Excel file in Kotlin
Example of reading data from the first sheet:
import org.apache.poi.ss.usermodel.*import org.apache.poi.xssf.usermodel.XSSFWorkbookimport java.io.FileInputStream
fun readExcel(filePath: String) { val file = FileInputStream(filePath) val workbook: Workbook = XSSFWorkbook(file) val sheet: Sheet = workbook.getSheetAt(0)
for (row in sheet) { for (cell in row) { when (cell.cellType) { CellType.STRING -> print("${cell.stringCellValue} ") CellType.NUMERIC -> print("${cell.numericCellValue} ") else -> print(" ") } } println() } workbook.close()}Creating an Excel file
Let's create a simple table with headers:
import org.apache.poi.xssf.usermodel.XSSFWorkbookimport java.io.FileOutputStream
fun createExcel() { val workbook = XSSFWorkbook() val sheet = workbook.createSheet("Data")
// Headers val headerRow = sheet.createRow(0) headerRow.createCell(0).setCellValue("Name") headerRow.createCell(1).setCellValue("Age") headerRow.createCell(2).setCellValue("City")
// Data val data = listOf( listOf("Anna", 25, "Moscow"), listOf("Ivan", 30, "SPb"), listOf("Maria", 22, "Kazan") )
data.forEachIndexed { index, rowData -> val row = sheet.createRow(index + 1) rowData.forEachIndexed { cellIndex, value -> row.createCell(cellIndex).setCellValue(value.toString()) } }
workbook.write(FileOutputStream("output.xlsx")) workbook.close()}2. poi-kotlin library — Kotlin-first wrapper
poi-kotlin (version 0.3.0) is a lightweight wrapper over Apache POI that adds extension functions and DSL syntax characteristic of Kotlin. Installation:
repositories { maven("https://jitpack.io")}dependencies { implementation("com.github.nicklausw.poi-kotlin:poi-kotlin:0.3.0")}Example with poi-kotlin
import com.github.nicklausw.poi.kotlin.*
fun dslExample() { val workbook = workbook { sheet("Report") { row { cell("Product") cell("Price") cell("Quantity") } row { cell("Laptop") cell(1200.0) cell(5) } row { cell("Mouse") cell(25.5) cell(10) } } } workbook.writeToFile("report.xlsx")}The code has become more readable, and the nested blocks sheet { row { ... } } resemble building HTML markup.
3. kotlinpoi library — functional approach
kotlinpoi (ver