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
- Open Visual Studio Code and create a new folder for your project (e.g.,
excel-reader), then open it in VS Code. - Create a
srcfolder inside your project root, then insidesrc, create a package folder namedcom.example.excel(or your preferred package name). - Inside the package folder, create a new Java file named
ExcelReader.java. - Open the Command Palette in VS Code (Ctrl+Shift+P or Cmd+Shift+P), type
Java: Create Maven Project, and select it. Choosequick-startas the archetype. This generates apom.xmlfile with basic structure. - Edit the
pom.xmlfile 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>
- Save
pom.xml. VS Code will automatically detect the change and prompt you to reload the Maven project. Click Reload or manually runmvn compilein the integrated terminal (View > Terminal). - Replace the contents of
ExcelReader.javawith 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());
}
}
}
- Create a
datafolder in your project root (same level assrc). - Place your Excel file (e.g.,
sample.xlsx) inside thedatafolder. Ensure it contains at least one row of data with text, numbers, or dates. - Right-click on
ExcelReader.javain the Explorer panel and select Run Java. Alternatively, open the integrated terminal and runmvn compile exec:java -Dexec.mainClass="com.example.excel.ExcelReader". - 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—
XSSFWorkbookis for .xlsx files only. For .xls files, useHSSFWorkbookand change the import and constructor accordingly. - Not placing the Excel file in the correct path. The code assumes the file is in
data/sample.xlsxrelative to the project root. Use absolute paths if needed, but relative paths are more portable. - Forgetting to add both
poiandpoi-ooxmldependencies. Only includingpoiwill cause aNoClassDefFoundErrorfor XML-related classes in .xlsx files. - Running the code without building the project first. Always run
mvn compileafter editingpom.xmlto ensure dependencies are downloaded and compiled. - Using Java 7 or lower. Apache POI 5.x requires Java 8+. Check your Java version with
java -versionin 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:javamatches the full class name including package. - "FileNotFoundException": Double-check the file path. Use an absolute path like
/Users/username/project/data/sample.xlsxon macOS/Linux orC:\Users\username\project\data\sample.xlsxon Windows to test if the relative path is the issue. - "NoClassDefFoundError: org/apache/poi/ss/usermodel/Workbook": Maven didn't download dependencies. Delete the
.m2folder in your home directory, then runmvn clean compileto 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
NumberFormatto format numeric values, or check ifDateUtil.isCellDateFormatted()is misidentifying numbers as dates.
Frequently Asked Questions
Can I read .xls files with this method?
Yes, but you must useHSSFWorkbook 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. UseWorkbook.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. UseDateUtil.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. Useworkbook.getSheetAt(index) for each sheet, or loop through workbook.sheetIterator() to process all sheets without knowing their count.