Skip to main content

How to generate excel sheet by using java

Introduction to Excel Generation in Java

Java Excel Generation Workflow Java Excel Generation Workflow 1 Determine Export Requirements Identify data structures, formats, and stakeholder reporting needs. 2 Select Appropriate Library Choose Apache POI SXSSF for large modern .xlsx enterprise datasets. 3 Map Data to Grid Coordinates Translate business records into programmatic rows and columns. 4 Configure Memory & Streams Implement disk-backed streaming to prevent OutOfMemoryError exceptions. 5 Export and Stream Output Deliver the styled spreadsheet securely to the client application.
Figure: Java Excel Generation Workflow

Generating Microsoft Excel documents programmatically is a frequent requirement in enterprise software development. Applications regularly need to export reporting data, financial ledgers, system audit logs, or user rosters into formats that business stakeholders can open, filter, and analyze. While CSV files serve simple text-export needs, they lack formatting capabilities, multiple sheets, column width adjustments, and cell styling.

Pick a language, then press Listen.

Historically, Java developers relied on basic libraries to write Excel files. However, modern enterprise applications have largely abandoned the legacy jxl.jar (JExcelAPI) library due to severe limitations: it only supports the older binary .xls format (Excel 97-2003), lacks updates for modern Java runtimes, and struggles with large datasets. Modern production systems use Apache POI for comprehensive Office Open XML (.xlsx) support. Despite this, understanding how programmatic spreadsheet generation functions from the ground up helps engineers grasp memory management, stream handling, and cell formatting principles.

This guide examines programmatic Excel generation. We will review the legacy JExcelAPI approach for historical context and map out how data parsing translates into grid coordinates. We will also analyze real-world edge cases like memory pressure, character encoding, and large record sets, ensuring your backend applications handle exports reliably without throwing OutOfMemoryError exceptions.

Evaluating Java Excel Generation Libraries

Before writing code, architectural choices must be made regarding which library fits your deployment targets. The choice typically balances file format requirements (.xls versus .xlsx), memory efficiency, and feature sets.

Library Supported Format Memory Footprint Active Maintenance Best Use Case
JExcelAPI (jxl.jar) .xls (Binary) High (Loads entire tree into RAM) Deprecated / Inactive Legacy maintenance only
Apache POI HSSF .xls (Binary) Moderate Active Legacy 97-2003 format generation
Apache POI XSSF / SXSSF .xlsx (XML-based) Low (SXSSF uses disk-backed streaming) Active Modern enterprise reports, large datasets

When dealing with modern cloud environments, infrastructure choices matter. If you containerize your reporting services, ensuring that your memory limits are correctly configured is critical. For instance, when running heavy export jobs, memory tuning parallels deploying microservices, similar to considerations required when Dockerizing a Spring Boot Application with MySQL.

Historical Implementation: Using JExcelAPI (jxl.jar)

To understand the mechanics of writing programmatic spreadsheets, let us examine a complete, production-grade example using the legacy JExcelAPI. While deprecated, this codebase demonstrates how raw string data can be parsed, transformed, and mapped into specific row and column coordinates inside a workbook.

In this implementation, an unformatted string containing pipe-delimited or comma-separated records is parsed. Each record is split, assigned styling (such as background colors and font definitions), and injected into cell indices.

package com.thbs.java.jxl;

import java.io.File;
import java.io.IOException;
import jxl.Workbook;
import jxl.format.Colour;
import jxl.write.Label;
import jxl.write.WritableCell;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

/**
 * Created By JavaTBrains
 * 
 * This Java class creates an Excel File output (.xls)
 * from a raw String input using JExcelAPI.
 */
public class CreateExcelSheet {

    public static void main(String[] args) {
        // Raw input simulating an unparsed data stream from a database or file
        String input = "100,subba reddy,MIS,Software Engineer END " +
                       "200,Nallamachu S,Java,Programmer END " +
                       "300,Reddy Nallamachu,MISTechmologies,Project Manager END";

        int counter = 0;
        File file = new File("E:/LOGS/excel.xls");

        try {
            // Initialize the writable workbook and sheet
            WritableWorkbook workbook = Workbook.createWorkbook(file);
            WritableSheet sheet = workbook.createSheet("Employee Data", 0);

            // Define header columns
            String[] header = { "Emp ID", "Name", "Department", "Designation" };

            // Configure cell formatting for headers (Lime background, Black Arial font)
            WritableCellFormat headerFormat = new WritableCellFormat();
            headerFormat.setBackground(Colour.LIME);

            WritableFont font = new WritableFont(WritableFont.ARIAL);
            font.setColour(Colour.BLACK);
            headerFormat.setFont(font);

            // Write headers to Row 0
            for (int i = 0; i < header.length; i++) {
                Label label = new Label(i, 0, header[i]);
                sheet.addCell(label);
                WritableCell cell = sheet.getWritableCell(i, 0);
                cell.setCellFormat(headerFormat);
            }

            // Split records by the "END" delimiter
            String[] inputArray = input.split("END");

            for (int i = 0; i < inputArray.length; i++) {
                String record = inputArray[i].trim();
                if (record.isEmpty()) {
                    continue;
                }
                
                counter++;
                int rowIndex = counter; // Row 0 is reserved for headers
                
                String[] fieldValuesArray = record.split(",");

                for (int j = 0; j < fieldValuesArray.length; j++) {
                    String value = fieldValuesArray[j].trim();
                    Label dataLabel = new Label(j, rowIndex, value);
                    sheet.addCell(dataLabel);
                }
            }

            // Write and close workbook resources
            workbook.write();
            workbook.close();
            
            System.out.println("Excel file generated successfully at: " + file.getAbsolutePath());

        } catch (IOException | WriteException e) {
            System.err.println("Error generating Excel sheet: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

Step-by-Step Code Breakdown

Analyzing the implementation above reveals several foundational steps required for any spreadsheet generation engine, regardless of whether you use JExcelAPI, Apache POI, or another underlying format writer:

  1. Workbook Initialization: The engine allocates a file handle via Workbook.createWorkbook(File). This sets up an output stream pointed directly to disk or memory.
  2. Sheet Creation: Workbooks consist of one or more worksheets. workbook.createSheet("Page1", 0) establishes a sheet named "Page1" at the zero-indexed position.
  3. Cell Styling and Formatting: Visual styling requires explicit object instantiation. WritableCellFormat and WritableFont encapsulate properties like background palette fills, borders, typography, and font colors. Separating format definitions from data insertion reduces heap overhead.
  4. Coordinate Mapping: Spreadsheets rely on cartesian coordinates: columns are represented by horizontal indices (X axis), and rows by vertical indices (Y axis). The Label class constructor accepts (column, row, stringValue) parameters.
  5. Data Parsing Loop: Incoming raw data must be tokenized. In our example, records are delimited by the literal string END, and individual fields are separated by commas. Nested loops iterate through these arrays to place values sequentially into matching spreadsheet cells.
  6. Resource Flushing and Closing: Calling workbook.write() flushes the internal buffers to the underlying file stream. Closing the workbook releases system file locks.

When working with modern data structures in Java, you can also leverage cleaner syntax features. If your application processes immutable data models before exporting them to spreadsheets, utilizing newer language features simplifies data transfer objects. For more details on language evolution, read about Java 17 Records and Pattern Matching with Examples.

Real-World Edge Cases to Consider

Writing functional code for a tutorial is straightforward, but production environments introduce edge cases that can crash JVM processes or corrupt output files. Consider the following scenarios when building reporting pipelines:

1. Memory Consumption and Large Datasets (OutOfMemoryError)

In-memory generators load the entire document structure into the JVM heap. If an export job queries 500,000 rows from a database and builds cell objects for every record, the application will quickly trigger an OutOfMemoryError. In production, switch to streaming APIs (such as Apache POI's SXSSFWorkbook), which write sliding windows of rows to disk and keep a minimal memory footprint.

2. Special Characters, Formula Injection, and CSV Injection

If user-supplied input strings begin with characters like =, +, -, or @, spreadsheet software may interpret the cell value as an executable formula. This introduces security risks (CSV/Formula injection). Always sanitize string inputs before passing them into cell labels if the data originates from untrusted user submissions.

3. Null Pointers and Malformed Delimiters

Data strings retrieved from external systems frequently contain trailing whitespace, unexpected null tokens, or irregular field counts. If record parsing encounters fewer fields than expected, ArrayIndexOutOfBounds exceptions occur. Wrap parsing loops in defensive null checks and ensure delimiter consistency across all input streams.

Troubleshooting Common Spreadsheet Generation Errors

Even with careful planning, runtime exceptions can occur during file generation. Here are common errors and their solutions:

  • java.io.FileNotFoundException (Access Denied): This occurs when the target directory does not exist or the application lacks write permissions. Ensure target folders are created programmatically using file.getParentFile().mkdirs() before instantiating the workbook.
  • jxl.write.WriteException: Attempt to write a cell with a null value: Legacy libraries throw exceptions if null strings are passed to cell constructors. Always sanitize inputs: replace null with an empty string "" before cell creation.
  • File Corruption Warnings in Excel: If Microsoft Excel displays a warning stating the file format or extension is invalid, verify that you are not writing HTML error pages or stack traces directly into the output stream during server-side web exports.

In enterprise architectures that rely on legacy application servers, managing external dependencies and database connections often requires specific configuration files. For example, legacy database setups may require explicit JNDI resource definitions, similar to the setup detailed in JNDI configuration for Tomcat 9 with Oracle.

Summary

Programmatic spreadsheet generation is a core capability for enterprise Java applications. While legacy libraries like JExcelAPI introduced developers to coordinate-based cell placement and basic styling, modern implementations rely on robust frameworks like Apache POI to handle complex XML structures and large datasets safely.

  • Understand the structural differences between legacy binary formats (.xls) and modern OpenXML formats (.xlsx).
  • Map raw data streams accurately into cartesian grid coordinates (column, row indices).
  • Protect JVM memory by implementing streaming strategies when exporting large record sets.
  • Sanitize all incoming text fields to prevent formula injection and parsing exceptions.

Comments

Popular posts from this blog

JVM, JRE and JDK in Java

Understanding JVM, JRE, and JDK in Java Every Java developer encounters three fundamental acronyms on their first day: JVM , JRE , and JDK . Misunderstanding these foundational components leads to runtime exceptions, deployment failures, and incorrect build environments. This guide breaks down the precise architectural boundaries, memory structures, and deployment requirements of each component. ▶ Listen English (India) English (US) Hindi Telugu Tamil Kannada Malayalam Bengali Marathi Gujarati Punjabi Urdu Arabic Spanish French German Portuguese Japanese Korean Chinese (Simplified) Pick a language, then press Listen. The core problem this guide solves is ambiguous environment configuration. Developers often attempt to run production applications using a Development Kit when a Runtime Environment suffices, or they deploy platform-incompatible binaries to minimal Li...

Prime, Fibonacci and Factorial number with example in java

Mastering Prime, Fibonacci, and Factorial Algorithms in Java Prime Number Validation Workflow Prime Number Validation Workflow 1 Boundary Check Verify if the input number is less than or equal to 1. 2 Even Number Check Check if divisible by 2 and return true only if number is 2. 3 Square Root Limit Calculate integer square root as the upper loop bound. 4 Odd Factor Loop Iterate through odd integers up to limit checking divisibility. Figure: Prime Number Validation Workflow Technical coding interviews frequently test foundational algorithmic competence through three classic mathematical problems: identifying prime numbers, generating Fibonacci sequences, and calculating factorials. While these concepts originate in basic arithmetic, writing production-grade Java code to solve them requires careful attention to time complexity, memory allocation, boundary conditions, and overflow behavior. This tutorial provides rigorous, optimized Java i...

How to insert images into database using JDBC?

How to Insert Images into a Database Using JDBC Storing binary data such as images, PDFs, and application assets is a frequent requirement in enterprise software engineering. While relational databases like MySQL are optimized for structured tabular text and numeric data, they also provide robust binary storage types—specifically BLOB (Binary Large Object) variants—to handle arbitrary byte streams. When interacting with relational stores through Java, the Java Database Connectivity (JDBC) API serves as the primary bridge. ▶ Listen English (India) English (US) Hindi Telugu Tamil Kannada Malayalam Bengali Marathi Gujarati Punjabi Urdu Arabic Spanish French German Portuguese Japanese Korean Chinese (Simplified) Pick a language, then press Listen. This technical guide demonstrates how to persist image files from a local file system directly into a MySQL database usin...