To read an Excel file in Java Spring Boot, add Apache POI as a dependency, create a service to handle file upload and parsing, then use POI's XSSFWorkbook to extract data from .xlsx files into Java objects for further processing.

What You'll Need

  • Java 11 or later
  • Spring Boot 2.7 or later
  • Apache POI 5.0 or later (for .xlsx support)
  • Maven or Gradle build tool
  • An Excel file in .xlsx format (older .xls requires HSSFWorkbook)

Step-by-Step

  1. Add Apache POI dependencies to your build file. For Maven, include:
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>5.2.5</version>
    </dependency>
    
    For Gradle:
    implementation 'org.apache.poi:poi-ooxml:5.2.5'
    
  2. Create a DTO (Data Transfer Object) class to hold the data from each row. For example, if reading employee data:
    public class EmployeeDTO {
        private String name;
        private String department;
        private double salary;
        // getters and setters
    }
  3. Create a service class to handle Excel reading. Use @Service annotation and inject any needed components:
    @Service
    public class ExcelReaderService {
        public List<EmployeeDTO> readExcelFile(MultipartFile file) throws IOException {
            List<EmployeeDTO> employees = new ArrayList<>();
            try (InputStream inputStream = file.getInputStream();
                 XSSFWorkbook workbook = new XSSFWorkbook(inputStream)) {
                
                XSSFSheet sheet = workbook.getSheetAt(0); // first sheet
                Iterator<Row> rowIterator = sheet.iterator();
                
                // Skip header row if present
                if (rowIterator.hasNext()) {
                    rowIterator.next(); // assume first row is header
                }
                
                while (rowIterator.hasNext()) {
                    Row row = rowIterator.next();
                    EmployeeDTO emp = new EmployeeDTO();
                    
                    // Assuming columns: 0=name, 1=department, 2=salary
                    Cell nameCell = row.getCell(0);
                    Cell deptCell = row.getCell(1);
                    Cell salaryCell = row.getCell(2);
                    
                    emp.setName(nameCell != null ? nameCell.getStringCellValue() : null);
                    emp.setDepartment(deptCell != null ? deptCell.getStringCellValue() : null);
                    emp.setSalary(salaryCell != null ? salaryCell.getNumericCellValue() : 0.0);
                    
                    employees.add(emp);
                }
            }
            return employees;
        }
    }
    
  4. Create a controller to handle file upload requests. Use @RestController and @PostMapping:
    @RestController
    @RequestMapping("/api/excel")
    public class ExcelController {
        
        @Autowired
        private ExcelReaderService excelReaderService;
        
        @PostMapping("/upload")
        public ResponseEntity<List<EmployeeDTO>> uploadExcel(@RequestParam("file") MultipartFile file) {
            try {
                if (file.isEmpty()) {
                    return ResponseEntity.badRequest().build();
                }
                
                // Optional: validate file type
                if (!file.getContentType().equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {
                    return ResponseEntity.badRequest().body(null);
                }
                
                List<EmployeeDTO> data = excelReaderService.readExcelFile(file);
                return ResponseEntity.ok(data);
            } catch (IOException e) {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
            }
        }
    }
    
  5. Test the endpoint using a tool like Postman or curl. Send a POST request to /api/excel/upload with the Excel file attached as form-data under the key "file". The response should be a JSON array of EmployeeDTO objects.

Common Mistakes

  • Using HSSFWorkbook for .xlsx files: HSSF only supports the older .xls format. Using it on .xlsx files will cause exceptions. Always use XSSFWorkbook for .xlsx.
  • Forgetting to close resources: Not using try-with-resources on InputStream or Workbook can lead to memory leaks. Always wrap them in try-with-resources blocks.
  • Assuming all cells have data: Calling getStringCellValue() on a numeric or blank cell throws exceptions. Always check for null and use appropriate getters based on cell type.
  • Ignoring header rows: Failing to skip the first row if it contains headers results in header data being treated as a record. Explicitly skip it if needed.
  • Not validating file type: Accepting any file without checking its MIME type or extension can lead to security risks or parsing errors on non-Excel files.

Tips

  • Use DataFormatter to safely get string values from any cell type: new DataFormatter().formatCellValue(cell) avoids type-checking headaches.
  • For large files, consider using SXSSFWorkbook (streaming mode) to reduce memory usage instead of XSSFWorkbook which loads the entire file into memory.
  • Validate data during parsing: check for empty required fields, invalid formats (e.g. salary as text), and log or skip problematic rows instead of failing the entire upload.
  • Return meaningful error messages in the controller: instead of just 500, tell the user if the file is corrupted, has wrong format, or missing columns.
  • Unit test your ExcelReaderService with a sample .xlsx file in src/test/resources to ensure parsing logic works before integrating with the controller.

Troubleshooting

  • Exception: Invalid header signature: This means you're trying to read an .xls file with XSSFWorkbook or vice versa. Confirm the file format and use HSSFWorkbook for .xls, XSSFWorkbook for .xlsx.
  • NullPointerException when reading cells: A cell is null because it's blank. Always check if row.getCell(index) returns null before calling methods on it.
  • OutOfMemoryError with large files: XSSFWorkbook loads the whole file. Switch to SXSSFWorkbook for writing or use event-based APIs (like XML parsing) for very large read-only files, or increase JVM heap size if appropriate.
  • Controller returns 400 Bad Request: Check if the file is empty, wrong type, or missing in the request. Ensure the frontend sends it as multipart/form-data with the correct parameter name.
  • Data looks wrong (e.g. numbers as strings): Excel stores dates as numbers; POI returns the raw numeric value. Use DateUtil.isCellDateFormatted(cell) to detect and convert properly.

Frequently Asked Questions

Can I read .xls files with this approach?

Yes, but you must use HSSFWorkbook instead of XSSFWorkbook, and include the poi artifact (not poi-ooxml) for legacy .xls support.

Do I need to configure anything in Spring Boot application.properties?

No special configuration is required for file upload or POI. Spring Boot handles MultipartFile automatically with Tomcat or Jetty embedded servers.

What if my Excel file has multiple sheets?

Use workbook.getSheetAt(index) or workbook.getSheet("name") to access a specific sheet, or loop through workbook.numberOfSheets() to process all.

Is it safe to accept Excel files from users in a web app?

Only if you validate the file type, scan for malicious content (e.g. macros), and limit file size. Never execute content from the file.

How do I handle password-protected Excel files?

Apache POI does not support reading password-protected files. You must remove protection externally before processing.

Can I read Excel files from a file path instead of upload?

Yes. Replace MultipartFile.getInputStream() with new FileInputStream("path/to/file.xlsx") in the service method.