EXCEL to CSV Converter using Javascript and PHP

All you have to do is upload the excel file and click on the convert button to convert the excel file to csv file. You will get the csv file.

We have used PHP server side language to convert excel file to csv format. We will first create an html file. We will use that file to upload the file and send it to the PHP file. In the PHP file we will convert the uploaded files to CSV format using the PHPExcel library.

How to Download PHPExcel Library?

There are many options available for download PHPExcel library. Checkout below links:

Excel to table conversion steps:

  1. Upload file
  2. Check file is valid or not.
  3. Sent for conversion
  4. Check how much Sheets in Excel file
  5. Convert all Sheets into CSV file
  6. Merge all CSV files into one files
  7. Download the Converted CSV file

How to get Excel file by user?


<input accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" type="file" id="file_upload">

How to find out file has been uploaded or not? If uploaded, then how to check if the file size is more or less than 2MB?

document.querySelector("#file_upload").onchange = function() {
    if(document.querySelector('#file_upload').files.length == 0) {
		alert('Error : No file selected');
		return;
	}
	var file = document.querySelector('#file_upload').files[0];
	
	if(file.size > 2*1024*1024) {
		alert('Error : Exceeded size 2MB');
		return;
	}
}

Send Excel file to PHP using AJAX:

var data = new FormData();
data.append('file', document.querySelector('#file_upload').files[0]);
var request = new XMLHttpRequest();
request.open('post', '../code/exceltojson.php');
request.addEventListener('load', function(e) {
    // code
});
request.send(data);

Check file is Excel or not in PHP

$valid = false;
$types = array('Excel2007', 'Excel5');
foreach ($types as $type) {
    $reader = PHPExcel_IOFactory::createReader($type);
    if ($reader->canRead($file)) {
        $valid = true;
        break;
    }
}

if ($valid) {
    // Excel file is Valid
} else {
    // Excel file is not valid
}

Convert file Excel to CSV:

$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objReader->load($file);

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');    

$index = 0;
$data = Array();
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {

    $objPHPExcel->setActiveSheetIndex($index);

    $outFile = "files/".str_replace(array("-"," "), "_", $worksheet->getTitle()) .".csv";

    $objWriter->setSheetIndex($index);
    $objWriter->save($outFile);
}

unlink($file);

SOURCE CODE:

excel-to-csv-converter.html


<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>

<div class="item-wrapper one">
<div class="item">
    <form action="exceltocsv.php" method="post" enctype="multipart/form-data">
        <div class="item-inner">
            <div class="item-content">
                <div class="image-upload"> <label style="cursor: pointer;" for="file_upload">
                        <div class="h-100">
                            <div class="dplay-tbl">
                                <div class="dplay-tbl-cell"> <i class="fa fa-cloud-upload"></i>
                                    <h5><b>Choose Your file to Upload</b></h5>
                                    <h6 class="mt-10 mb-70">Or Drop Your File Here</h6>
                                </div>
                            </div>
                        </div>
                        <!--upload-content--> <input accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" type="file" name="excelfile" id="file_upload" class="image-input" required>
                    </label> </div>
            </div>
            <!--item-content-->
        </div>
        <!--item-inner-->
    </form>
</div>
<!--item-->
</div>
<progress id="progress" value="0"></progress>

<div id="result"></div>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

<script>
    document.querySelector("#progress").style.display = "none";

    $(document).ready(function() {
        document.querySelector("#file_upload").onchange = function() {
        if(document.querySelector('#file_upload').files.length == 0) {
            alert('Error : No file selected');
            return;
        }
        var file = document.querySelector('#file_upload').files[0];
        
        if(file.size > 2*1024*1024) {
            alert('Error : Exceeded size 2MB');
            return;
        }

        if (document.querySelector("#pre") !== null) {
            document.querySelector("#pre").remove();
        }

        var data = new FormData();
        data.append('file', document.querySelector('#file_upload').files[0]);
        document.querySelector("#progress").style.display = "block";
        var request = new XMLHttpRequest();
        request.open('post', '../code/code.php?type=exceltocsv');
        
        request.upload.addEventListener('progress', function(e) {
            var percent_complete = (e.loaded / e.total)*100;
            document.querySelector("#progress").max = 100;
            document.querySelector("#progress").value = percent_complete;
        });

        request.addEventListener('load', function(e) {
            
            let obj = JSON.parse(request.response);
            if (obj['status'] == 'success') {
                let result = "<ul>";
                let data = obj["files"];
                for (let i = 0; i < data.length; i++) {
                    result += "<li><a href=\"files/"+ data[i] +".csv\">Sheet: "+ data[i] +" Download Link</a></li>";
                }
                result += "</ul><br>";
                document.querySelector("#result").innerHTML = result;
            }
            document.querySelector('#file_upload').value = "";
            document.querySelector("#progress").value = 0;
            document.querySelector("#progress").style.display = "none";

            document.querySelector('#file_upload').value = "";
        });
        request.send(data);
        
    };
    });
</script>


excel-to-csv-converter.php


ini_set('memory_limit', '2000M');
        
require_once 'Classes/PHPExcel/IOFactory.php';

if (isset($_FILES["file"])) {
    
    $file = "files/".basename($_FILES["file"]["name"]);
    move_uploaded_file($_FILES["file"]["tmp_name"], $file);
    
    $valid = false;
    $types = array('Excel2007', 'Excel5');
    foreach ($types as $type) {
        $reader = PHPExcel_IOFactory::createReader($type);
        if ($reader->canRead($file)) {
            $valid = true;
            break;
        }
    }
    
    if ($valid) {
        
        $objReader = PHPExcel_IOFactory::createReader('Excel2007');
        $objPHPExcel = $objReader->load($file);
    
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');    
    
        $index = 0;
        $data = Array();
        foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
    
            $objPHPExcel->setActiveSheetIndex($index);
    
            // write out each worksheet to it's name with CSV extension
            $outFile = "files/".str_replace(array("-"," "), "_", $worksheet->getTitle()) .".csv";
            $objWriter->setSheetIndex($index);
            $objWriter->save($outFile);
            $data[] = str_replace(array("-"," "), "_", $worksheet->getTitle());
            $index++;
        }
        $temp = Array();
        $temp["status"] = "success";
        $temp["files"] = $data;
        echo json_encode($temp);
    } else {
        echo "{\"status\":\"Error\", \"reason\":\"Not Valid Excel file.\"}";
    }
    
} else {
    echo "{\"status\":\"Error\", \"reason\":\"Please select file.\"}";
}