All TalkersCode Topics

Follow TalkersCode On Social Media

How To Read Data From CSV File In HTML

Last Updated : Jul 1, 2023

How To Read Data From CSV File In HTML

In this article we will show you the solution of how to read data from CSV file in HTML, an HTML file input called a FileUpload control and an HTML button called Upload make up the HTML markup.

The JavaScript upload function is invoked when the button is clicked. The file's validity as a valid CSV or text file is first checked inside the function.

The browser's compatibility with the HTML5 File API is then verified.

Once all of the aforementioned checks have been passed, the CSV file's contents are read as a text string, which is then divided into sections by commas and newline characters before being presented as just an HTML table.

The most prevalent file format for exchanging information or data across programming languages is CSV, which stands for comma-separated values.

Moreover, you can use CSV to store data in databases or spreadsheets. JavaScript can read CSV files using HTML5's FileReader API.

CSV files can be read from either a remote or local location. FileReader API is used to open local files, and XMLHttpRequest is used to download remote files.

Data of CSV file format has been provided, and the objective is to use PHP to show this CSV file data in the web browser.

We will use the fgetcsv() function that show the information from the CSV file in the web browser.

A text file called a "Comma Separated Value" (CSV) contains data contents.The file extension (.csv) makes it possible to save data inside a tabular format.

Each line from such an open file is parsed using the fgetcsv() method, which looks for CSV fields.

It's a simple text file with a list of information in it.Between programmes, these files are routinely used to transport data.

Step By Step Guide On How To Read Data From CSV File In HTML :-

<!DOCTYPE html&g;
<html&g;
  <head&g;
    <meta name="viewport" content="width=device-width, initial-scale=1"&g;
    <title&g;CSV to HTML Table | talkerscode</title&g;
  </head&g;
  <body&g;
    <h2&g;Upload a CSV file to display in HTML Table</h2&g;
    <input type="file" id="file_upload" /&g;
    <button onclick="upload()"&g;Upload</button&g;
    <br&g;
    <br&g;
    <table id="display_csv_data" border="1"&g;</table&g;
    <script&g;
      function upload() {
        var files = document.getElementById('file_upload').files;
        if(files.length==0){
          alert("Please choose any file...");
          return;
        }
        var filename = files[0].name;
        var extension = filename.substring(filename.lastIndexOf(".")).toUpperCase();
        if (extension == '.CSV') {
            csvFileToJSON(files[0]);
        }else{
            alert("Please select a valid csv file.");
        }
      }
      function csvFileToJSON(file){
          try {
            var reader = new FileReader();
            reader.readAsBinaryString(file);
            reader.onload = function(e) {
                var jsonData = [];
                var headers = [];
                var rows = e.target.result.split("\r\n");
                for (var i = 0; i < rows.length; i++) {
                    var cells = rows[i].split(",");
                    var rowData = {};
                    for(var j=0;j<cells.length;j++){
                        if(i==0){
                            var headerName = cells[j].trim();
                            headers.push(headerName);
                        }else{
                            var key = headers[j];
                            if(key){
                                rowData[key] = cells[j].trim();
                            }
                        }
                    }
                    if(i!=0){
                        jsonData.push(rowData);
                    }
                }
                displayJsonToHtmlTable(jsonData);
                }
            }catch(e){
                console.error(e);
            }
      }
      function displayJsonToHtmlTable(jsonData){
        var table=document.getElementById("display_csv_data");
        if(jsonData.length&g;0){
            var headers = Object.keys(jsonData[0]);
            var htmlHeader='<thead&g;<tr&g;';
            for(var i=0;i<headers.length;i++){
                htmlHeader+= '<th&g;'+headers[i]+'</th&g;';
            }
            htmlHeader+= '<tr&g;</thead&g;';
            var htmlBody = '<tbody&g;';
            for(var i=0;i<jsonData.length;i++){
                var row=jsonData[i];
                htmlBody+='<tr&g;';
                for(var j=0;j<headers.length;j++){
                    var key = headers[j];
                    htmlBody+='<td&g;'+row[key]+'</td&g;';
                }
                htmlBody+='</tr&g;';
            }
            htmlBody+='</tbody&g;';
            table.innerHTML=htmlHeader+htmlBody;
        }else{
            table.innerHTML='There is no data in CSV';
        }
      }
    </script&g;
  </body&g;
</html&g;
  1. The browser is informed of the HTML version we are using in our first line, which is <HTML&g;. Tags are the foundation of HTML documents. Following the title tag in the <head&g; tag, the script tag must be entered between the opening and closing brackets. Then enter the JavaScript function.
  2. Next comes the body tag, which defines the body of the webpage. You can create this same content for your site in one specific location.
  3. Then we started the method of uploading a csv file.
  4. Then we create a button for uploading.
  5. Then we create a table using borders.
  6. After that, a <script&g; tag can be used to include us on an HTML page.
  7. After that, the data or information is displayed on the website by using the JavaScript function that was called from the HTML code. This is why we can use form input tags to call JavaScript functions besides their names.
  8. Then we start a Method to upload a valid csv file.
  9. Then we Here calling another method to read CSV file into json
  10. Then we define Method to read csv file and convert it into JSON
  11. After that displaying the json result into the HTML table.
  12. Then we see Methods to display the data in the HTML Table.
  13. Finally, after closing all tags, /script&g;/body&g;/html&g; but also code should be executed.

Conclusion :-

The data from a CSV file must occasionally be displayed into HTML table format.

As a result, we will learn how to use Javascript to show CSV file data inside a basic HTML table and a Bootstrap table.

To read the CSV file, we will employ the FileReader class' readAsBinaryString() function.

Let's say we have an existing CSV file (Employee.csv).

I hope this article on how to read data from csv file in html helps you and the steps and method mentioned above are easy to follow and implement.