Add Row Data to Columns Using Apache POI: A Comprehensive Guide

Abstract: Demonstrates how to populate Excel columns with row data using Apache POI in Java.

Created: 2026-10-20 by
You can add row data to columns in an Excel sheet using Apache POI by creating a workbook, accessing the appropriate sheet, and iterating through your data source. For each row, you create a new row object in the sheet and populate cells with the corresponding values from your dataset. This approach ensures that data is correctly aligned into columns rather than being appended as a single long row, providing a structured tabular format for your Java applications.

Setting Up the Project Dependencies

Before writing any code, you must ensure that the necessary Apache POI libraries are included in your project. The most common way to manage these dependencies is through Maven or Gradle. If you are using Maven, you need to add the poi and poi-ooxml artifacts to your pom.xml file. The poi library handles the basic file formats, while poi-ooxml is required for working with modern Excel files (XLSX). Here is the correct dependency configuration:
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>5.2.3</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.2.3</version>
</dependency>
Notice that we use standard XML escaping characters like < and >. It is critical to avoid syntax errors such as &lt; which will cause build failures. Additionally, always specify a stable version number to prevent unexpected breaking changes in future updates. If you are using Gradle, the equivalent implementation would be implementation 'org.apache.poi:poi:5.2.3' and implementation 'org.apache.poi:poi-ooxml:5.2.3'.

Creating the Workbook and Sheet

Once your dependencies are set up, the first step in the coding process is to instantiate the workbook. In Apache POI, workbooks represent the entire Excel file. You should use try-with-resources to ensure that the file streams are closed properly after execution, preventing resource leaks and file locking issues.
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;

public class ExcelWriter {
    public static void main(String[] args) {
        String filePath = "output.xlsx";
        
        // Create workbook using try-with-resources
        try (Workbook workbook = new XSSFWorkbook();
             FileOutputStream outputStream = new FileOutputStream(filePath)) {
            
            // Create a sheet named "Data"
            Sheet sheet = workbook.createSheet("Data");
            
            // Proceed to add data here
            
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
In this snippet, we create an XSSFWorkbook instance, which is suitable for .xlsx files. We also open a FileOutputStream to write the final file. The try-with-resources block automatically closes both the workbook and the output stream when the block exits, whether normally or due to an exception. Inside the block, we create a sheet using workbook.createSheet(). This method returns a Sheet object that we will use to manipulate rows and cells.

Populating Rows and Columns

To add row data to columns, you need to iterate through your data structure. Assume you have a list of objects or arrays representing your rows. For each item in your data source, you create a new row in the Excel sheet. Then, for each column value, you create a cell within that row and set its value.
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import java.util.List;
import java.util.ArrayList;

// Sample data: List of arrays where each array represents a row
List rowData = new ArrayList<>();
rowData.add(new String[]{"Name", "Age", "City"}); // Header
rowData.add(new String[]{"Alice", "30", "New York"});
rowData.add(new String[]{"Bob", "25", "London"});

int rowNum = 0;
for (String[] data : rowData) {
    Row row = sheet.createRow(rowNum++);
    int colNum = 0;
    for (String field : data) {
        Cell cell = row.createCell(colNum++);
        cell.setCellValue(field);
    }
}
This loop demonstrates the core logic. sheet.createRow(rowNum) creates a new row at the specified index. The variable rowNum increments with each iteration to place data in subsequent rows. Inside the inner loop, row.createCell(colNum++) creates a cell at the specific column index. cell.setCellValue(field) assigns the string value to the cell. This method effectively maps your data structure into a grid format, ensuring that each piece of data lands in the correct column for its respective row.

Handling Different Data Types

While strings are common, Excel supports various data types including numbers, booleans, and dates. Apache POI provides different methods on the Cell interface to handle these types appropriately. Using the correct setter ensures that Excel interprets the data correctly, allowing for proper sorting and formatting. For numeric values, use cell.setCellValue(doubleValue). For boolean values, use cell.setCellValue(booleanValue). If you need to insert a date, you can use cell.setCellValue(java.util.Date), but note that you may need to configure the cell style to display the date correctly. It is important to check the type of your data before setting the value to avoid casting exceptions or incorrect displays.
Cell numCell = row.createCell(1);
numCell.setCellValue(42.5);

Cell boolCell = row.createCell(2);
boolCell.setCellValue(true);
When dealing with mixed data types in a single row, ensure that your data parsing logic matches the expected type for each column. Mismatched types can lead to runtime errors or silent failures where the cell appears empty or contains garbage data. Always validate your input data before passing it to the Apache POI setters.

Saving and Closing Resources

After populating all the rows and columns, you must save the workbook to the output stream. As shown in the earlier example, calling workbook.write(outputStream) writes the in-memory representation of the spreadsheet to the file system. This step is crucial because without it, no data is persisted to disk. Finally, ensure that all resources are closed. In the try-with-resources example provided earlier, the workbook and output stream are closed automatically. However, if you are not using try-with-resources, you must manually call workbook.close() and outputStream.close() in a finally block or similar structure. Failure to close these resources can lead to memory leaks and locked files that cannot be opened by other processes. For more advanced formatting, consider exploring how to Fill an Excel Cell based on data in two other cells to automate content generation. Additionally, if you need to summarize the data you just wrote, you might look into Summarizing max. values for each row in an excel table techniques.

Frequently Asked Questions

How do I append data to an existing Excel file?

You cannot directly append to a file using the same API easily; instead, you read the existing file into a Workbook object, modify it, and then write it back out. Use WorkbookFactory.create(inputStream) to load an existing file. After making your changes, write the modified workbook to a new file or overwrite the original.

What happens if I exceed the maximum number of rows in Excel?

Excel has a limit of 1,048,576 rows per sheet. If you attempt to create a row beyond this limit, Apache POI will throw an IllegalArgumentException. To handle large datasets, consider splitting your data across multiple sheets or using a database instead of Excel.

Can I set column widths automatically?

Yes, you can use sheet.autoSizeColumn(columnIndex) to adjust the width of a column to fit its content. However, this method can be slow for large sheets. A better approach for performance is to calculate the optimal width manually or set fixed widths using sheet.setColumnWidth().

How do I handle null values in my data?

If your data source contains nulls, check for them before calling setCellValue. You can either skip creating the cell entirely or set it to an empty string using cell.setCellValue(""). Leaving a cell unset results in a blank cell in Excel, which is often the desired behavior for missing data.

Is Apache POI thread-safe?

No, instances of Workbook, Sheet, and Row are not thread-safe. You should not share these objects between multiple threads. If you need concurrent access, create separate workbook instances for each thread or use synchronization mechanisms to ensure only one thread modifies the workbook at a time.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More