Excel files come in two main formats: .xls
(the older binary format) and .xlsx
(the newer XML - based format). When reading Excel files in Kotlin, you need to choose a library that can handle both formats effectively.
The most popular library for working with Excel files in the Java and Kotlin ecosystems is Apache POI. Apache POI provides a rich set of APIs to read, write, and manipulate Excel files. It has different components for handling different Microsoft Office file formats, including HSSF for .xls
files and XSSF for .xlsx
files.
To follow along with the examples in this post, you need to have the following:
build.gradle.kts
file:dependencies {
implementation("org.apache.poi:poi:5.2.3")
implementation("org.apache.poi:poi - ooxml:5.2.3")
}
You may need to read Excel files containing historical sales data, customer information, or sensor readings. By reading these files in Kotlin, you can perform various data analysis tasks such as calculating statistics, generating reports, or visualizing the data.
When migrating data from an Excel - based system to a new database or application, you need to read the Excel files and transform the data into a suitable format for the target system.
In automation scripts, you may need to read Excel files to get configuration data, test cases, or input parameters.
Apache POI provides a straightforward way to read Excel files. The general steps are as follows:
FileInputStream
to read the Excel file.Workbook
object based on the file format (HSSFWorkbook for .xls
or XSSFWorkbook for .xlsx
).Sheet
from the Workbook
.Sheet
to read the data.import org.apache.poi.ss.usermodel.*
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import java.io.File
import java.io.FileInputStream
fun main() {
// Step 1: Create a FileInputStream to read the Excel file
val file = File("example.xlsx")
val fis = FileInputStream(file)
// Step 2: Create a Workbook object
val workbook: Workbook = XSSFWorkbook(fis)
try {
// Step 3: Get the first sheet from the workbook
val sheet: Sheet = workbook.getSheetAt(0)
// Step 4: Iterate over the rows and cells
for (row in sheet) {
for (cell in row) {
// Get the cell value based on its type
val cellValue = when (cell.cellType) {
CellType.STRING -> cell.stringCellValue
CellType.NUMERIC -> {
if (DateUtil.isCellDateFormatted(cell)) {
cell.dateCellValue.toString()
} else {
cell.numericCellValue.toString()
}
}
CellType.BOOLEAN -> cell.booleanCellValue.toString()
CellType.FORMULA -> cell.cellFormula
else -> ""
}
print("$cellValue\t")
}
println()
}
} finally {
// Close the workbook and the input stream
workbook.close()
fis.close()
}
}
In this code:
FileInputStream
to read the Excel file.XSSFWorkbook
object because we are dealing with a .xlsx
file.When reading Excel files, there may be various errors such as file not found, incorrect file format, or corrupted files. Make sure to handle these errors gracefully in your code.
Always close the Workbook
and FileInputStream
after you are done reading the Excel file to avoid resource leaks. You can use the try - finally
block or the Kotlin use
function for this purpose.
If you are dealing with large Excel files, consider using the SXSSF API provided by Apache POI. SXSSF is a streaming API that can reduce the memory footprint by writing rows to disk instead of keeping them all in memory.
Reading Excel files in Kotlin is a common and important task in many software development projects. By using the Apache POI library, you can easily read both .xls
and .xlsx
files. We have explored the core concepts, typical usage scenarios, and best practices for reading Excel files in Kotlin. With the knowledge and code examples provided in this post, you should be able to apply this technique effectively in your own projects.