简体   繁体   English

如何使用Javascript将csv和xlsx文件读取为Html表格形式

[英]How to read csv and xlsx file to Html table form with Javascript

In my script, user can upload their CSV file and view the content with the HTML form.在我的脚本中,用户可以上传他们的 CSV 文件并使用 HTML 表单查看内容。 They are also able to add a new column at the first row of the HTML table.他们还可以在 HTML 表的第一行添加一个新列。 For example, when a user uploaded an excel file that contains 2 records, the script will automatically add a new row named Serial infront of the existing record.例如,当用户上传一个包含 2 条记录的 excel 文件时,脚本会自动在现有记录前面添加一个名为Serial的新行。 For now when user upload a csv file, it will show a weird empty column in the HTML table but it worked fine with xlsx format.现在,当用户上传 csv 文件时,它会在 HTML 表中显示一个奇怪的空列,但它在 xlsx 格式下工作正常。 Does anyone know what the cause of this issue ?有谁知道这个问题的原因是什么?

My Excel file:我的 Excel 文件:

在此处输入图片说明

Example (When a user uploads xlsx. format file, it will display correctly with no issue):示例(当用户上传 xlsx. 格式文件时,它会正确显示,没有问题): 在此处输入图片说明

But if the user uploads a .csv file, there is a weird empty column will appear:但是如果用户上传一个.csv文件,会出现一个奇怪的空列: 在此处输入图片说明

So how can I make the null column to dissapear?那么我怎样才能让空列消失呢? to work on both CSV and xlsx format?使用 CSV 和 xlsx 格式? Now it seems like it only works for xlsx files.现在它似乎只适用于 xlsx 文件。

Full Code完整代码

<!DOCTYPE HTML>
<html>

<head>


  <script type="text/javascript" src="https://unpkg.com/xlsx@0.15.1/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>

Replace your JS library with latest version用最新版本替换你的 JS 库

https://cdn.jsdelivr.net/npm/xlsx/dist/xlsx.full.min.js

Have a try.试试。

I think your running version's default behavior does not treat the file with single column as CSV.我认为您的运行版本的默认行为不会将具有单列的文件视为 CSV。 Try multiple columns with comma separator, it works.尝试使用逗号分隔符的多列,它有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM