To read and write data from an Excel sheet using Java, you can use the Apache POI library. Here are the basic steps:
Add the POI dependencies to your project: In your build tool (Maven, Gradle, etc.), add the POI dependencies for reading and writing Excel files. For example, in Maven, you can add the following dependencies to your pom.xml file:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
2.Create a workbook object: Create a Workbook object for the Excel file you want to read from or write to. You can choose between HSSFWorkbook for .xls files and XSSFWorkbook for .xlsx files.
// Example: Create a new XSSFWorkbook for reading
FileInputStream inputStream = new FileInputStream("data.xlsx");
Workbook workbook = new XSSFWorkbook(inputStream);
// Example: Create a new XSSFWorkbook for writing
Workbook workbook = new XSSFWorkbook();
3. Read data from the cells: To read data from an Excel sheet, you can use the getCell() method of the Row object to get a Cell object for each cell, and then use the getStringCellValue(), getNumericCellValue(), or getDateCellValue() method of the Cell object to get the cell value.
// Example: Read data from a cell
Sheet sheet = workbook.getSheet("Sheet1");
Row row = sheet.getRow(0); // Row 0 is the first row
Cell cell = row.getCell(0); // Column 0 is the first column
String value = cell.getStringCellValue();
System.out.println(value);
4. Write data to the cells: To write data to an Excel sheet, you can use the setCellValue() method of the Cell object to set the cell value.
// Example: Write data to a cell
Sheet sheet = workbook.createSheet("Sheet1");
Row row = sheet.createRow(0); // Row 0 is the first row
Cell cell = row.createCell(0); // Column 0 is the first column
cell.setCellValue("Hello, World!");
// Example: Write data to multiple cells
Row row1 = sheet.createRow(1);
Cell cell1 = row1.createCell(0);
cell1.setCellValue("John");
Cell cell2 = row1.createCell(1);
cell2.setCellValue(30);
Row row2 = sheet.createRow(2);
Cell cell3 = row2.createCell(0);
cell3.setCellValue("Mary");
Cell cell4 = row2.createCell(1);
cell4.setCellValue(25);
5. Save the workbook: Finally, you need to save the changes to the workbook by writing it to a file or a stream.
// Example: Save the workbook to a file
FileOutputStream outputStream = new FileOutputStream("data.xlsx");
workbook.write(outputStream);
workbook.close();
outputStream.close();
These are the basic steps for reading and writing data from an Excel sheet using Java and Apache POI. You can customize the code based on your specific requirements.
Thank you!
nice article