简体   繁体   中英

Is there anyway I can attach an Excel file to my HTML or Javascript, to be used as a database?

I want to auto-populate a person data on my website, and I need it to get data from an Excel file. So that, the data on my website will automatically change if its updated on Excel. Sadly I need to do this using only vanilla Javascript.

No. You cannot* use vanilla JavaScript to pull data from an Excel file located on your server. However, if you want to populate data on your page from a markup file and use something like JSON or XML , that is much more doable and I think answers your use case. Here's a simple example:

data.js :

var xhr = new XMLHttpRequest();

xhr.responseType = 'json';
xhr.open('GET', 'data.json');

xhr.onload = function() {
  build_table(xhr.response);
}

function build_table(data) {
  var result = '';
  for (var i = 0; i < data.length; i++) {
    result += build_row(data[i]);
  }
  document.getElementById('data').innerHTML += result;
}

function build_row(data) {
  var result = '<tr>';
  result += '<td>' + data.firstname + '</td>';
  result += '<td>' + data.lastname + '</td>';
  result += '<td>' + data.country + '</td>';
  result += '</tr>';
  return result;
}

index.html :

<head>
  <title>AJAX Example</title>
  <script src="data.js"></script>
</head>
<body>
  <table id="data">
    <tr>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Country</th>
    </tr>
  </table>
</body>

data.json :

[
    {
        "firstname": "John",
        "lastname": "Smith",
        "country": "United States"
    },
    {
        "firstname": "Alice",
        "lastname": "Lastname",
        "country": "Germany"
    },
    {
        "firstname": "Bob",
        "lastname": "Bobson",
        "country": "United States"
    }
]

If you must work with Excel data, I would use the Python openpyxl and json libraries to read and write your data to this markup file, respectively, though I'm sure similar libraries exist for the language of your choice.

I don't think the following applies, but just for the sake of completeness: if it's an option for you, you could have your webserver build this HTML before it's served, using one of a number of options for your data access layer ( openpyxl being one of them).

* It is, literally speaking, possible to access an .xlsx file via AJAX, unzip it using zip.js or similar, and process its XML contents. I do not think you want to do this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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