EXCEL to HTML Table Converter using Javascript and PHP

In Excel to HTML table converter you can convert file with just one click. There is no problem with date format. And with that comes the code on how to convert all the sheets in an excel file at once.

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. Convert CSV to JSON file
  7. JSON to HTML table
  8. Use HTML beautifier for look beautiful

How to upload file:

<input type="file" name="excelfile" onchange="checkfile()">

Check file is Valid or not:

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 file for Conversion:

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/exceltojson.php');
request.addEventListener('load', function(e) {
    // response
});
request.send(data);

Check how much Sheets in Excel file:

foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
    $objWriter->setSheetIndex($index);
    
    // Sheet Name
    $sheet = $worksheet->getTitle();
}

Convert all sheets into CSV format:

function csvtojson($file) {
    if (($handle = fopen($file, "r")) !== FALSE) {
        $csvs = [];
        while(! feof($handle)) {
           $csvs[] = fgetcsv($handle);
        }
        $datas = [];
        $column_names = [];
        foreach ($csvs[0] as $single_csv) {
            $column_names[] = $single_csv;
        }
        foreach ($csvs as $key => $csv) {
            if ($key === 0) {
                continue;
            }
            foreach ($column_names as $column_key => $column_name) {
                $datas[$key-1][$column_name] = $csv[$column_key];
            }
        }
        $json = json_encode($datas);
        fclose($handle);
        return $json;
    }
}

Convert CSV to JSON file:

$data = Array();

$data[$worksheet->getTitle()] = json_decode(csvtojson($outFile), true);

Convert JSON data format to HTML Table format:

function buildHtmlTable(json) {
    result += "<table border=\"1\">";
    var col = [];
    for (var i = 0; i < json.length; i++) {
        result += "<tr>";
        for (var key in json[i]) {
            let temp = json[i];
            if (col.indexOf(key) === -1) {
                result += "<th>"+ key +"</th>";
                col.push(key);
            } else {
                result += "<td>"+ temp[key] +"</td>";
            }
        }
        result += "</tr>";
    }
    
    result += "</table>";
}

Use HTML beautifier for look beautiful

<script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.11.0/beautify-html.js"></script>
var beautify_html = html_beautify(result);
document.querySelector("#result").value = beautify_html;

SOURCE CODE:

index.html

<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.11.0/beautify-html.js"></script>

<h1>EXCEL to HTML Table Converter using PHP</h1>
                        
<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>
<div class="form-group">
    <label>Result:</label>
    <textarea id="result" class="prettyprint form-control" rows="10"></textarea>
</div>

<script>
    let result = "";
    
    $(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/exceltohtml.php');

        request.addEventListener('load', function(e) {
            
            var obj = JSON.parse(this.responseText);
            let keys = Object.keys(obj);
            for (let i = 0; i < keys.length; i++) {
                result += "<p>Table of Sheet: "+ keys[i] +"</p>";
                buildHtmlTable(obj[keys[i]]);
            }
            var beautify_html = html_beautify(result);
            document.querySelector("#result").value = beautify_html;
            
            document.querySelector('pre').style.maxHeight = "280px";
            document.querySelector('pre').setAttribute("id", "pre");
            document.querySelector('#file_upload').value = "";

            document.querySelector('#file_upload').value = "";
        });
        request.send(data);
        
    };
    });
    
    function buildHtmlTable(json) {
        result += "<table id=\"excelDataTable\" border=\"1\">";
        var col = [];
        for (var i = 0; i < json.length; i++) {
            result += "<tr>";
            for (var key in json[i]) {
                let temp = json[i];
                if (col.indexOf(key) === -1) {
                    result += "<th>"+ key +"</th>";
                    col.push(key);
                } else {
                    result += "<td>"+ temp[key] +"</td>";
                }
            }
            result += "</tr>";
        }
        
        result += "</table><br>";
    }
</script>

exceltohtml.php

<?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[$worksheet->getTitle()] = json_decode(csvtojson($outFile), true);
    
            $index++;
            unlink($outFile);
        }
    
        echo json_encode($data);
        unlink($file);
        
    } else {
        echo "{\"status\":\"Error\", \"reason\":\"Not Valid Excel file.\"}";
    }
} else {
    echo "{\"status\":\"Error\", \"reason\":\"Please select file.\"}";
}

function csvtojson($file) {
    if (($handle = fopen($file, "r")) !== FALSE) {
        $csvs = [];
        while(! feof($handle)) {
           $csvs[] = fgetcsv($handle);
        }
        $datas = [];
        $column_names = [];
        foreach ($csvs[0] as $single_csv) {
            $column_names[] = $single_csv;
        }
        foreach ($csvs as $key => $csv) {
            if ($key === 0) {
                continue;
            }
            foreach ($column_names as $column_key => $column_name) {
                $datas[$key-1][$column_name] = $csv[$column_key];
            }
        }
        $json = json_encode($datas);
        fclose($handle);
        return $json;
    }
}
?>