Java can read Excel files in Visual Studio Code by using the Apache POI library, which provides APIs to parse .xls and .xlsx formats. This enables automation of data extraction from spreadsheets for reporting, configuration parsing, or batch processing. No additional IDE or proprietary software is required—only a Java development environment and the correct dependencies.

What You'll Need

  • Java Development Kit (JDK) 8 or higher installed
  • Visual Studio Code (any recent version)
  • Apache POI library (version 5.2.4 or later recommended)
  • A valid Excel file (.xls or .xlsx) for testing
  • Java Extension Pack for VS Code (includes Language Support for Java, Debugger for Java, and Maven Support)

Step-by-Step

  1. Open Visual Studio Code and create a new folder for your project (e.g., excel-reader), then open it in VS Code.
  2. Create a src folder inside your project root, then inside src, create a package folder named com.example.excel (or your preferred package name).
  3. Inside the package folder, create a new Java file named ExcelReader.java.
  4. Open the Command Palette in VS Code (Ctrl+Shift+P or Cmd+Shift+P), type Java: Create Maven Project, and select it. Choose quick-start as the archetype. This generates a pom.xml file with basic structure.
  5. Edit the pom.xml file to include Apache POI dependencies. Inside the <dependencies> section, add:
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>5.2.4</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.2.4</version>
</dependency>
  1. Save pom.xml. VS Code will automatically detect the change and prompt you to reload the Maven project. Click Reload or manually run mvn compile in the integrated terminal (View > Terminal).
  2. Replace the contents of ExcelReader.java with the following code:
package com.example.excel;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.IOException;

public class ExcelReader {
    public static void main(String[] args) {
        String filePath = "data/sample.xlsx"; // Change this path to your file

        try (FileInputStream fis = new FileInputStream(filePath);
             Workbook workbook = new XSSFWorkbook(fis)) {

            Sheet sheet = workbook.getSheetAt(0);
            for (Row row : sheet) {
                for (Cell cell : row) {
                    switch (cell.getCellType()) {
                        case STRING:
                            System.out.print(cell.getStringCellValue() + "\t");
                            break;
                        case NUMERIC:
                            if (DateUtil.isCellDateFormatted(cell)) {
                                System.out.print(cell.getDateCellValue() + "\t");
                            } else {
                                System.out.print(cell.getNumericCellValue() + "\t");
                            }
                            break;
                        case BOOLEAN:
                            System.out.print(cell.getBooleanCellValue() + "\t");
                            break;
                        case FORMULA:
                            System.out.print(cell.getCellFormula() + "\t");
                            break;
                        default:
                            System.out.print("\t");
                    }
                }
                System.out.println();
            }

        } catch (IOException e) {
            System.err.println("Error reading Excel file: " + e.getMessage());
        }
    }
}
  1. Create a data folder in your project root (same level as src).
  2. Place your Excel file (e.g., sample.xlsx) inside the data folder. Ensure it contains at least one row of data with text, numbers, or dates.
  3. Right-click on ExcelReader.java in the Explorer panel and select Run Java. Alternatively, open the integrated terminal and run mvn compile exec:java -Dexec.mainClass="com.example.excel.ExcelReader".
  4. Check the Output panel or terminal for printed rows of data from your Excel file. Each cell value appears tab-separated, with rows on new lines.

Common Mistakes

  • Using the wrong file extension—XSSFWorkbook is for .xlsx files only. For .xls files, use HSSFWorkbook and change the import and constructor accordingly.
  • Not placing the Excel file in the correct path. The code assumes the file is in data/sample.xlsx relative to the project root. Use absolute paths if needed, but relative paths are more portable.
  • Forgetting to add both poi and poi-ooxml dependencies. Only including poi will cause a NoClassDefFoundError for XML-related classes in .xlsx files.
  • Running the code without building the project first. Always run mvn compile after editing pom.xml to ensure dependencies are downloaded and compiled.
  • Using Java 7 or lower. Apache POI 5.x requires Java 8+. Check your Java version with java -version in the terminal.

Tips

  • Use cell.toString() for a quick fallback if you don't need type-specific handling, though it may lose formatting precision.
  • For large files, consider using SXSSFWorkbook (streaming mode) to reduce memory usage.
  • Always wrap file access in try-with-resources to prevent file handle leaks.
  • Install the Java Test Runner extension to write and run unit tests for your Excel parser using JUnit.
  • Use VS Code's built-in debugger to set breakpoints on cell processing logic and inspect variable values live.
  • Keep your Excel file simple during testing—avoid merged cells, complex formulas, or embedded objects until the basic reader works.

Troubleshooting

  • "Cannot find or load main class": Verify your package declaration matches the folder structure. Ensure the class name in exec:java matches the full class name including package.
  • "FileNotFoundException": Double-check the file path. Use an absolute path like /Users/username/project/data/sample.xlsx on macOS/Linux or C:\Users\username\project\data\sample.xlsx on Windows to test if the relative path is the issue.
  • "NoClassDefFoundError: org/apache/poi/ss/usermodel/Workbook": Maven didn't download dependencies. Delete the .m2 folder in your home directory, then run mvn clean compile to force redownload.
  • VS Code doesn't recognize Java code: Install the Java Extension Pack from the Extensions Marketplace. Restart VS Code after installation.
  • Excel file opens but shows no output: Check if the sheet is empty or if the file is password-protected. Apache POI cannot read encrypted files.
  • Numbers appear as decimals with many zeros: Use NumberFormat to format numeric values, or check if DateUtil.isCellDateFormatted() is misidentifying numbers as dates.

Frequently Asked Questions

Can I read .xls files with this method?

Yes, but you must use HSSFWorkbook instead of XSSFWorkbook and change the import to org.apache.poi.hssf.usermodel.HSSFWorkbook. The rest of the code remains identical.

Do I need Maven?

Not strictly, but it's the easiest way to manage dependencies in VS Code. You can manually download JAR files and add them to your classpath, but this is error-prone and not recommended for beginners.

Can I write to Excel files too?

Yes, Apache POI supports writing. Use Workbook.write() with FileOutputStream to create or modify files. The same dependencies work for reading and writing.

Why does my date show as a number?

Excel stores dates as numeric values internally. Use DateUtil.isCellDateFormatted(cell) to detect them, then call cell.getDateCellValue() to get a proper Java Date object.

Can I read multiple sheets in one file?

Yes. Use workbook.getSheetAt(index) for each sheet, or loop through workbook.sheetIterator() to process all sheets without knowing their count.

Is this method secure for production use?

Yes, Apache POI is stable and widely used in enterprise environments. Avoid reading untrusted files without validation, as maliciously crafted spreadsheets can cause memory exhaustion or code injection if processed unsafely.