To read an Excel file in Java, you can use the Apache POI library. Apache POI is a Java library that allows you to read and write Microsoft Office documents, such as Excel, PowerPoint, and Word files.
Here is an example of how you can use Apache POI to read an Excel file in Java:
import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class ExcelReader { public static void main(String[] args) throws IOException { FileInputStream inputStream = new FileInputStream(new File("example.xlsx")); Workbook workbook = new XSSFWorkbook(inputStream); Sheet sheet = workbook.getSheetAt(0); for (Row row : sheet) { for (Cell cell : row) { System.out.print(cell.getStringCellValue() + " "); } System.out.println(); } workbook.close(); inputStream.close(); } }
In this example, the main
method opens an input stream to the Excel file using the FileInputStream
class. It then creates a Workbook
object using the XSSFWorkbook
class, which is part of the Apache POI library and is used to read .xlsx files (the latest version of Excel).
The Workbook
object is used to get the first sheet of the Excel file using the getSheetAt
method. The sheet is then iterated over using a loop, and each row is iterated over using another loop.
The cell values are extracted using the getStringCellValue
method of the Cell
class and printed to the console using the System.out.print
method.
This code will read the data from the Excel file and print it to the console. You can modify the code to store the data in a data structure or perform other operations with it.
Keep in mind that this is just one way to read an Excel file in Java. You can use different techniques and libraries to achieve the same result, such as using the HSSFWorkbook
class to read .xls files (the older version of Excel) or using a different library to parse the Excel file.