Paperwork

5 Ways to Read Excel Data with Java

5 Ways to Read Excel Data with Java
How To Read Data In Excel Sheet Using Java

Overview of Java Libraries for Excel Data Processing

Read Data From Excel In Java

When it comes to working with Excel files in Java, developers are fortunate to have several robust libraries at their disposal. These libraries provide the tools necessary to read, write, and manipulate Excel files efficiently. Here’s an overview of five popular libraries:

  • Apache POI - An open-source library for the Microsoft Office format. It’s versatile, handling both .xls and .xlsx formats.
  • JExcelApi - Another open-source library which focuses on reading, writing, and modifying .xls format files.
  • OpenCSV - Though primarily for CSV, it can be adapted to handle Excel formats when saved as CSV.
  • JXLS - Specializes in generating Excel reports from XML templates, but can also read Excel files.
  • XlsToMYSQL - A tool for converting Excel files to MySQL, though its main focus is data migration.

1. Using Apache POI to Read Excel Data

Reading Excel Data And Store In Database Java Programming Youtube
Apache POI Logo

Apache POI is one of the most popular libraries for working with Excel files in Java. It supports both the older .xls format (HSSF) and the newer .xlsx format (XSSF). Here’s how you can use POI to read data from an Excel file:


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) throws IOException {
        // Load the Excel workbook
        FileInputStream file = new FileInputStream("sample.xlsx");
        Workbook workbook = new XSSFWorkbook(file);
        Sheet sheet = workbook.getSheetAt(0);

        // Iterate through rows and cells
        for (Row row : sheet) {
            for (Cell cell : row) {
                // Handle different cell types
                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;
                    default:
                        System.out.print("Empty" + "\t");
                        break;
                }
            }
            System.out.println();
        }
        workbook.close();
        file.close();
    }
}

💡 Note: Ensure that the appropriate Apache POI jar files are included in your project's classpath or declared in your build tool.

2. JExcelApi: An Alternative for .xls Files

Java Read Or Delete Document Properties From Excel

JExcelApi is a bit more lightweight than Apache POI and focuses on the older Excel .xls format. Here’s how to use JExcelApi:


import jxl.*;

import java.io.File;

public class JExcelReader {
    public static void main(String[] args) throws Exception {
        // Open the Excel file
        Workbook workbook = Workbook.getWorkbook(new File("sample.xls"));
        Sheet sheet = workbook.getSheet(0);

        // Iterate through cells
        for (int i = 0; i < sheet.getRows(); i++) {
            for (int j = 0; j < sheet.getColumns(); j++) {
                Cell cell = sheet.getCell(j, i);
                System.out.print(cell.getContents() + "\t");
            }
            System.out.println();
        }
        workbook.close();
    }
}

3. OpenCSV: Reading CSV Files Generated from Excel

Read Data From Excel Sheet Using Java Code Riset

Excel files can be easily saved as CSV, making them readable with tools like OpenCSV. This method is particularly useful when dealing with large datasets where Excel compatibility isn’t critical. Here’s a sample:


import com.opencsv.CSVReader;
import com.opencsv.CSVReaderBuilder;

import java.io.FileReader;
import java.io.IOException;

public class CSVReaderExample {
    public static void main(String[] args) throws IOException {
        // Create a CSV reader
        FileReader filereader = new FileReader("sample.csv");
        CSVReader csvReader = new CSVReaderBuilder(filereader).withSkipLines(1).build();
        
        // Read CSV line by line
        String[] nextLine;
        while ((nextLine = csvReader.readNext()) != null) {
            for (String string : nextLine) {
                System.out.print(string + "\t");
            }
            System.out.println();
        }
        csvReader.close();
    }
}

4. JXLS: For Excel Reporting

Java Map Remove While Iterator Get Latest Map Update

JXLS is primarily known for generating reports using Excel templates, but it also allows reading from Excel files for report generation purposes. Here’s how you might use JXLS:


import org.jxls.common.Context;
import org.jxls.expression.JexlExpressionEvaluator;
import org.jxls.transform.Transformer;
import org.jxls.transform.poi.PoiTransformer;
import org.jxls.util.JxlsHelper;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

public class JXLSReader {
    public static void main(String[] args) throws Exception {
        List persons = new ArrayList<>();
        persons.add(new Person("John", "Doe", 30));
        persons.add(new Person("Jane", "Smith", 25));

        // Open template Excel file
        FileInputStream templateInputStream = new FileInputStream("template.xlsx");
        FileOutputStream outputStream = new FileOutputStream("output.xlsx");
        Transformer transformer = PoiTransformer.createTransformer(templateInputStream, outputStream);
        
        // Prepare context
        Context context = new Context();
        context.putVar("persons", persons);

        // Process Excel file
        JxlsHelper helper = JxlsHelper.getInstance();
        helper.processTemplate(context, transformer);
        
        // Reading data would be done through XML mapping or direct access to the transformer's sheet
        templateInputStream.close();
        outputStream.close();
    }
}

class Person {
    private String firstName, lastName;
    private int age;
    // Constructor and getters/setters omitted for brevity
}

📌 Note: While JXLS excels at generating reports, it can be more complex to set up for just reading Excel data compared to other libraries.

5. XlsToMYSQL: Directly Importing Excel Data into MySQL

Github Thedan06 Java Read Excel Files This Is A Simple Java Program

This tool, though more niche, provides a straightforward way to convert Excel data into a MySQL database, which can be useful for bulk data import. Here’s an example of how it might be used:


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.PreparedStatement;

public class ExcelToMySQL {
    public static void main(String[] args) {
        // Database credentials
        String url = "jdbc:mysql://localhost:3306/yourdatabase";
        String user = "username";
        String password = "password";
        
        try {
            // Load the JDBC driver
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection(url, user, password);

            // Assuming 'sheet1' from 'example.xlsx' needs to be imported
            // Your implementation would vary based on how you read the Excel file
            PreparedStatement ps = con.prepareStatement("INSERT INTO yourtable (column1, column2) VALUES (?, ?)");
            
            // Here, you would loop through the Excel data and execute the prepared statement
            // ps.setString(1, excelData[row][col1]);
            // ps.setString(2, excelData[row][col2]);
            // ps.executeUpdate();
            
            con.close();
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

By now, you’ve learned how to read Excel data using different Java libraries, each with its strengths. Apache POI offers comprehensive functionality for both .xls and .xlsx files. JExcelApi simplifies reading older formats. OpenCSV is ideal when data is exported to CSV. JXLS offers a robust reporting tool alongside reading capabilities, and XlsToMYSQL streamlines data import into databases. Each method has its pros and cons, so the choice depends on your specific requirements, like the Excel file format, the complexity of data handling, and whether you need additional features like formatting or data manipulation.

To recap: - Apache POI and JExcelApi provide core functionalities for Excel file manipulation. - OpenCSV is perfect for CSV files, which are often Excel-derived. - JXLS specializes in Excel report generation but can also read data. - XlsToMYSQL is focused on importing Excel data into MySQL databases.

This variety of tools ensures you can select the best fit for your project, whether for batch processing, real-time data manipulation, or reporting needs.

Which library should I choose for my project?

Reading Excel Data In Java Riset
+

Choose Apache POI for comprehensive Excel handling, JExcelApi for older formats, OpenCSV for simple CSV exports, JXLS for reporting, or XlsToMYSQL for direct database import.

Can these libraries handle large Excel files?

Java Export Excel Data To Word Tables With Formatting
+

Apache POI, JExcelApi, and OpenCSV have streaming capabilities to manage large files, though performance might still be a concern with very large datasets.

Do these libraries support all Excel features?

How To Read Excel Files In Java Using Apache Poi Callicoder
+

Apache POI covers most Excel features, while other libraries might be more limited in functionality like charts, conditional formatting, etc.

Related Articles

Back to top button