Convert XLS to CSV in Java – Apache POI Complete Guide (2024)

Convert XLS to CSV in Java with Apache POI – Full Code Examples

Introduction

Java developers typically use Apache POI — the industry-standard library for reading and writing Microsoft Office files — to convert XLS and XLSX files to CSV format. This guide walks you through complete, production-ready code examples.

Maven Dependency Setup

Add these dependencies to your pom.xml:

<dependency>

    <groupId>org.apache.poi</groupId>

    <artifactId>poi</artifactId>

    <version>5.2.5</version>

</dependency>

<dependency>

    <groupId>org.apache.poi</groupId>

    <artifactId>poi-ooxml</artifactId>

    <version>5.2.5</version>

</dependency>

<dependency>

    <groupId>org.apache.commons</groupId>

    <artifactId>commons-csv</artifactId>

    <version>1.10.0</version>

</dependency>

Complete Java XLS to CSV Converter

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

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

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.io.*;

import java.util.*;

public class XlsToCsvConverter {

    public static void convert(String xlsPath, String csvPath) throws IOException {

        FileInputStream fis = new FileInputStream(xlsPath);

        Workbook workbook;

        if (xlsPath.endsWith(‘.xlsx’)) {

            workbook = new XSSFWorkbook(fis);

        } else {

            workbook = new HSSFWorkbook(fis);

        }

        Sheet sheet = workbook.getSheetAt(0);

        DataFormatter formatter = new DataFormatter();

        try (PrintWriter writer = new PrintWriter(new FileWriter(csvPath))) {

            for (Row row : sheet) {

                List<String> cells = new ArrayList<>();

                for (Cell cell : row) {

                    String val = formatter.formatCellValue(cell);

                    if (val.contains(‘,’) || val.contains(‘”‘)) {

                        val = ‘”‘ + val.replace(‘”‘, ‘””‘) + ‘”‘;

                    }

                    cells.add(val);

                }

                writer.println(String.join(‘,’, cells));

            }

        }

        workbook.close();

        fis.close();

        System.out.println(‘Conversion complete: ‘ + csvPath);

    }

    public static void main(String[] args) throws IOException {

        convert(‘input.xlsx’, ‘output.csv’);

    }

}

Handling Multiple Sheets in Java

for (int i = 0; i < workbook.getNumberOfSheets(); i++) {

    Sheet sheet = workbook.getSheetAt(i);

    String sheetName = sheet.getSheetName();

    String outFile = sheetName + ‘.csv’;

    // … write each sheet to its own CSV file

}

Frequently Asked Questions (FAQs)

Does Apache POI support both .xls and .xlsx formats?

Yes. Use HSSFWorkbook for .xls (Excel 97-2003) files and XSSFWorkbook for .xlsx (Excel 2007+) files. You can detect the format from the file extension or use WorkbookFactory.create() which automatically handles both.

How do I handle special characters in Java XLS to CSV conversion?

Use Apache Commons CSV library for proper CSV encoding. It automatically handles commas, quotes, and newlines inside cell values according to the RFC 4180 standard.

Internal Linking Suggestions

  • Convert XLS to CSV with Python – /xls-to-csv-python
  • XLS to CSV PHP Guide – /xls-to-csv-php
  • Convert XLS to CSV – Main Guide – /convert-xls-to-csv

Convert XLS to CSV Using PHP – PhpSpreadsheet Guide (2024)

Primary Keyword: convert xls to csv php | Volume: 20 | Difficulty: Low | Cluster: 4 (Support)

Meta TitleConvert XLS to CSV with PHP – PhpSpreadsheet Full Code Guide
Meta DescriptionLearn to convert XLS and XLSX files to CSV using PHP and PhpSpreadsheet. Includes Composer setup, code examples, and web upload integration.

Introduction

PHP developers building web applications often need server-side XLS to CSV conversion. PhpSpreadsheet is the modern, actively maintained library for this task — a successor to the popular PHPExcel library.

Installation with Composer

composer require phpoffice/phpspreadsheet

Basic XLS to CSV Conversion in PHP

<?php

require ‘vendor/autoload.php’;

use PhpOffice\PhpSpreadsheet\IOFactory;

use PhpOffice\PhpSpreadsheet\Writer\Csv;

function convertXlsToCsv(string $inputPath, string $outputPath): void {

    $spreadsheet = IOFactory::load($inputPath);

    $sheet = $spreadsheet->getActiveSheet();

    $writer = new Csv($spreadsheet);

    $writer->setSheetIndex(0);

    $writer->setDelimiter(‘,’);

    $writer->setEnclosure(‘”‘);

    $writer->setLineEnding(“\r\n”);

    $writer->setUseBOM(true); // UTF-8 BOM for Excel compatibility

    $writer->save($outputPath);

    echo “Converted successfully to: $outputPath”;

}

convertXlsToCsv(‘input.xlsx’, ‘output.csv’);

?>

Web Upload and Convert with PHP

<?php

if ($_SERVER[‘REQUEST_METHOD’] === ‘POST’ && isset($_FILES[‘xls_file’])) {

    $uploadedFile = $_FILES[‘xls_file’][‘tmp_name’];

    $originalName = pathinfo($_FILES[‘xls_file’][‘name’], PATHINFO_FILENAME);

    $outputPath = ‘converted/’ . $originalName . ‘.csv’;

    require ‘vendor/autoload.php’;

    use PhpOffice\PhpSpreadsheet\IOFactory;

    use PhpOffice\PhpSpreadsheet\Writer\Csv;

    $spreadsheet = IOFactory::load($uploadedFile);

    $writer = new Csv($spreadsheet);

    $writer->save($outputPath);

    // Send file to browser for download

    header(‘Content-Type: text/csv’);

    header(‘Content-Disposition: attachment; filename=”‘ . $originalName . ‘.csv”‘);

    readfile($outputPath);

    unlink($outputPath); // Clean up

}

?>

Convert All Sheets to Separate CSV Files in PHP

$sheetCount = $spreadsheet->getSheetCount();

for ($i = 0; $i < $sheetCount; $i++) {

    $sheetName = $spreadsheet->getSheet($i)->getTitle();

    $writer = new Csv($spreadsheet);

    $writer->setSheetIndex($i);

    $writer->save($sheetName . ‘.csv’);

    echo “Saved: $sheetName.csv\n”;

}

Frequently Asked Questions (FAQs)

Is PhpSpreadsheet free to use commercially?

Yes. PhpSpreadsheet is released under the MIT License, which allows free use in commercial projects with no restrictions or royalties.

Can PhpSpreadsheet handle large XLS files?

Yes, but large files (50MB+) may require increasing PHP memory limit. Add ini_set(‘memory_limit’, ‘512M’) at the top of your script. For very large files, consider streaming readers like PhpSpreadsheet’s ReadFilter to process rows in chunks.

What is the difference between PHPExcel and PhpSpreadsheet?

PhpSpreadsheet is the direct successor to PHPExcel. PHPExcel is no longer maintained and has security vulnerabilities. Always use PhpSpreadsheet for new projects.

Internal Linking Suggestions

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top