Wednesday, 30 January 2013

Reading data from CSV File using JavaScript



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
        <title>Reading Data from CSV File</title>
        <style type="text/css">
            div
            {
                float: left;
                width: 250px;
            }
        </style>
        <script type="text/javascript">
            function readCSVFile() {
                var csvData = new Array();
                var csvFilePath = "F:\\Data.csv";

                var fso = new ActiveXObject('Scripting.FileSystemObject');
                var iStream = fso.OpenTextFile(csvFilePath, 1, true, 0);
                for (var n = 0; !iStream.AtEndOfStream; n++) {
                    csvData[n] = iStream.ReadLine();
                    showData(csvData[n]);
                }
                iStream.Close();
            }

            function showData(data) {
                var csvData = data.split(",");
                document.getElementById('firstNames').innerHTML += "<br />" + csvData[0];
                document.getElementById('middleNames').innerHTML += "<br />" + csvData[1];
                document.getElementById('lastNames').innerHTML += "<br />" + csvData[2];
            }
        </script>
    </head>
    <body onload="javascript: readCSVFile()">
        <div id="firstNames"><b><i>First Names:</i></b></div>
        <div id="middleNames"><b><i>Middle Names:</i></b></div>
        <div id="lastNames"><b><i>Last Names:</i></b></div>
    </body>
</html>

Note: This code works only in Internet Explorer

1 comment: