Home > Back-end >  How to add new column and row in Html table with JavaScript
How to add new column and row in Html table with JavaScript

Time:09-28

I have an excel csv file:

enter image description here

This csv file will be uploaded on my website and allow them to view the content of the csv in html table form. Example:

enter image description here

As you can user successfully uploaded their csv file and view the content with the html form. Is it possible to add a new column at the first row of the html table? For example, when user uploaded a csv file that contain 2 records, the script will automatic add a new row named Serial infront of the existing record.

Expected Output:

enter image description here

What I've tried: I added table_output = '<th>' ['Serial' row] '</th>' inside the for(var row = 0; row < sheet_data.length; row ) but the result is not what I want. I want the header to be <th> and record below are <td>. enter image description here

My full code (Html & Javascript)

<!DOCTYPE HTML>
<html>
<head>


    <script type="text/javascript" src="https://unpkg.com/[email protected]/dist/xlsx.full.min.js"></script>
</head>
<body>
    <div class="container">
        <h2 class="text-center mt-4 mb-4">Convert Excel to HTML Table using JavaScript</h2>
        <div class="card">
            <div class="card-header"><b>Select Excel File</b></div>
            <div class="card-body">
                
                <input type="file" id="excel_file" />

            </div>
        </div>
        <div id="excel_data" class="mt-5"></div>
    </div>
</body>
</html>

<script>

const excel_file = document.getElementById('excel_file');

excel_file.addEventListener('change', (event) => {

    if(!['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel'].includes(event.target.files[0].type))
    {
        document.getElementById('excel_data').innerHTML = '<div class="alert alert-danger">Only .xlsx or .xls file format are allowed</div>';

        excel_file.value = '';

        return false;
    }

    var reader = new FileReader();

    reader.readAsArrayBuffer(event.target.files[0]);

    reader.onload = function(event){

        var data = new Uint8Array(reader.result);

        var work_book = XLSX.read(data, {type:'array'});

        var sheet_name = work_book.SheetNames;

        var sheet_data = XLSX.utils.sheet_to_json(work_book.Sheets[sheet_name[0]], {header:1});

        if(sheet_data.length > 0)
        {
            var table_output = '<table class="table table-striped table-bordered">';

            for(var row = 0; row < sheet_data.length; row  )
            {

                table_output  = '<tr>';
        table_output  = '<th>' ['Serial' row] '</th>'

                for(var cell = 0; cell < sheet_data[row].length; cell  )
                {
            
                    if(row == 0)
                    {

                        table_output  = '<th>' sheet_data[row][cell] '</th>';

                    }
                    else
                    {

                        table_output  = '<td>' sheet_data[row][cell] '</td>';

                    }

                }

                table_output  = '</tr>';

            }

            table_output  = '</table>';

            document.getElementById('excel_data').innerHTML = table_output;
        }

        excel_file.value = '';

    }

});

</script>

CodePudding user response:

Use if statement to manage heading and columns

const excel_file = document.getElementById('excel_file');
    
    excel_file.addEventListener('change', (event) => {
    
        if(!['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel'].includes(event.target.files[0].type))
        {
            document.getElementById('excel_data').innerHTML = '<div class="alert alert-danger">Only .xlsx or .xls file format are allowed</div>';
    
            excel_file.value = '';
    
            return false;
        }
    
        var reader = new FileReader();
    
        reader.readAsArrayBuffer(event.target.files[0]);
    
        reader.onload = function(event){
    
            var data = new Uint8Array(reader.result);
    
            var work_book = XLSX.read(data, {type:'array'});
    
            var sheet_name = work_book.SheetNames;
    
            var sheet_data = XLSX.utils.sheet_to_json(work_book.Sheets[sheet_name[0]], {header:1});
    
            if(sheet_data.length > 0)
            {
                var table_output = '<table class="table table-striped table-bordered">';
    
                for(var row = 0; row < sheet_data.length; row  )
                {
    
                    table_output  = '<tr>';
              if(row == 0)
               {
                 table_output  = '<th>Serial</th>'
                }
                else{ 
                     '<td>' ['Serial' row] '</td>'
                    }
    
                    for(var cell = 0; cell < sheet_data[row].length; cell  )
                    {
                
                        if(row == 0)
                        {
    
                            table_output  = '<th>' sheet_data[row][cell] '</th>';
    
                        }
                        else
                        {
    
                            table_output  = '<td>' sheet_data[row][cell] '</td>';
    
                        }
    
                    }
    
                    table_output  = '</tr>';
    
                }
    
                table_output  = '</table>';
    
                document.getElementById('excel_data').innerHTML = table_output;
            }
    
            excel_file.value = '';
    
        }
    
    });

CodePudding user response:

<!DOCTYPE HTML>
<html>
<head>


    <script type="text/javascript" src="https://unpkg.com/[email protected]/dist/xlsx.full.min.js"></script>
</head>
<body>
    <div class="container">
        <h2 class="text-center mt-4 mb-4">Convert Excel to HTML Table using JavaScript</h2>
        <div class="card">
            <div class="card-header"><b>Select Excel File</b></div>
            <div class="card-body">
                
                <input type="file" id="excel_file" />

            </div>
        </div>
        <div id="excel_data" class="mt-5"></div>
    </div>
</body>
</html>

<script>

const excel_file = document.getElementById('excel_file');

excel_file.addEventListener('change', (event) => {

    if(!['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel'].includes(event.target.files[0].type))
    {
        document.getElementById('excel_data').innerHTML = '<div class="alert alert-danger">Only .xlsx or .xls file format are allowed</div>';

        excel_file.value = '';

        return false;
    }

    var reader = new FileReader();

    reader.readAsArrayBuffer(event.target.files[0]);

    reader.onload = function(event){

        var data = new Uint8Array(reader.result);

        var work_book = XLSX.read(data, {type:'array'});

        var sheet_name = work_book.SheetNames;

        var sheet_data = XLSX.utils.sheet_to_json(work_book.Sheets[sheet_name[0]], {header:1});

        if(sheet_data.length > 0)
        {
            var table_output = '<table class="table table-striped table-bordered">';
            var opening_tag = '';
            var closing_tag = '';

            for(var row = 0; row < sheet_data.length; row  )
            {

             if(row == 0)
                    {
                      opening_tag = '<th><td><Serial></td>';
                      closing_tag = '</th>';
                    }
              else
                    {
                      opening_tag = '<tr>';
                      closing_tag = '</tr>';
                    }
       
                for(var cell = 0; cell < sheet_data[row].length; cell  )
                {
            
                    if(row == 0)
                    {

                        table_output  = opening_tag   '<td>' sheet_data[row][cell] '</td>'   closing_tag;

                    }
                    else
                    {

                        table_output  = opening_tag   '<td>Serial'   row   '</td><td>' sheet_data[row][cell] '</td>'   closing_tag;

                    }

                }

            }

            table_output  = '</table>';

            document.getElementById('excel_data').innerHTML = table_output;
        }

        excel_file.value = '';

    }

});

</script>

CodePudding user response:

I updated your code. Please check if this is what you need.

<!DOCTYPE HTML>
<html>

<head>


  <script type="text/javascript" src="https://unpkg.com/[email protected]/dist/xlsx.full.min.js"></script>
</head>

<body>
  <div class="container">
    <h2 class="text-center mt-4 mb-4">Convert Excel to HTML Table using JavaScript</h2>
    <div class="card">
      <div class="card-header"><b>Select Excel File</b></div>
      <div class="card-body">

        <input type="file" id="excel_file" />

      </div>
    </div>
    <div id="excel_data" class="mt-5"></div>
  </div>
</body>

</html>

<script>
  const excel_file = document.getElementById('excel_file');

  excel_file.addEventListener('change', (event) => {

    if (!['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel'].includes(event.target.files[0].type)) {
      document.getElementById('excel_data').innerHTML = '<div class="alert alert-danger">Only .xlsx or .xls file format are allowed</div>';

      excel_file.value = '';

      return false;
    }

    var reader = new FileReader();

    reader.readAsArrayBuffer(event.target.files[0]);

    reader.onload = function(event) {

      var data = new Uint8Array(reader.result);

      var work_book = XLSX.read(data, {
        type: 'array'
      });

      var sheet_name = work_book.SheetNames;

      var sheet_data = XLSX.utils.sheet_to_json(work_book.Sheets[sheet_name[0]], {
        header: 1
      });

      if (sheet_data.length > 0) {
        var table_output = '<table class="table table-striped table-bordered">';

        for (var row = 0; row < sheet_data.length; row  ) {

          table_output  = '<tr>';
          if (row == 0) {
            table_output  = '<th>'   ['Serial']   '</th>'
          } else {
            table_output  = '<td>'   row   '</td>'
          }

          for (var cell = 0; cell < sheet_data[row].length; cell  ) {

            if (row == 0) {

              table_output  = '<th>'   sheet_data[row][cell]   '</th>';

            } else {

              table_output  = '<td>'   sheet_data[row][cell]   '</td>';

            }

          }

          table_output  = '</tr>';

        }

        table_output  = '</table>';

        document.getElementById('excel_data').innerHTML = table_output;
      }

      excel_file.value = '';

    }

  });
</script>

  • Related