How to read Excel cell having Date with Apache POI?

How to read Excel cell having Date with Apache POI?

To read an Excel cell containing a date using Apache POI, you can use the DateCellValue or getLocalDateTimeCellValue methods, depending on whether you want to work with the date as a Date or LocalDateTime object. Here's an example of how to do this:

import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileInputStream; import java.io.IOException; import java.util.Date; public class ReadExcelDateCell { public static void main(String[] args) { try (FileInputStream fileInputStream = new FileInputStream("your_excel_file.xlsx"); Workbook workbook = new XSSFWorkbook(fileInputStream)) { Sheet sheet = workbook.getSheetAt(0); // Assuming you're reading the first sheet // Assuming the date is in cell A1 (0-based index) Row row = sheet.getRow(0); Cell cell = row.getCell(0); if (cell.getCellType() == CellType.NUMERIC && DateUtil.isCellDateFormatted(cell)) { // If the cell contains a date value Date dateValue = cell.getDateCellValue(); System.out.println("Date: " + dateValue); } else { // Handle other cell types or non-date values System.out.println("Cell does not contain a date."); } } catch (IOException e) { e.printStackTrace(); } } } 

In this example:

  1. We open an Excel file using FileInputStream and create a Workbook object (assuming you are using the newer .xlsx format, which is represented by XSSFWorkbook).

  2. We select a sheet (in this case, the first sheet) and a specific cell (e.g., A1) where you expect the date.

  3. We check if the cell contains a date value using getCellType() and DateUtil.isCellDateFormatted(cell).

  4. If the cell contains a date, we retrieve the date using getDateCellValue().

  5. Finally, we print the date value.

Make sure to replace "your_excel_file.xlsx" with the actual path to your Excel file and adjust the sheet and cell references as needed.


More Tags

selector joi uitextfield mongoose-schema scheduling react-apollo php-5.5 venn-diagram file-not-found amazon-cloudwatchlogs

More Java Questions

More Internet Calculators

More Mortgage and Real Estate Calculators

More Dog Calculators

More Financial Calculators