SheetJS CE Test

Writing xlsx books with SheetJS CE

by Nicolas Mancilla

HTML

<script src="https://unpkg.com/xlsx/dist/xlsx.full.min.js"></script>
<label>Name: <input type="text" id="name" value="John" /></label><br />
<label>Last Name: <input type="text" id="lastName" value="Doe" /></label><br />
<button id="saveBook" type="button">
  Save
</button>

JavaScript

function saveBook() {
  const name = document.getElementById('name').value;
  const lastName = document.getElementById('lastName').value;

  if (!name || !lastName) {
    return;
  }
  
  // A multidimensional array represents the data.
  // Each array is a new row and each item on the
  // array is a different column (cell).
  const data = [
    // A     B
    ["Name", "Last Name"], // Row 1
    [name, lastName] // Row 2
    // Row N
  ];

  // Creates the sheet data
  const ws = XLSX.utils.aoa_to_sheet(data);
  // Create a new book where to append the data.
  const wb = XLSX.utils.book_new();
  
  // Append the sheet (second param) to the book (first param)
  // with the specified name (third param)
  XLSX.utils.book_append_sheet(wb, ws, "Test Sheet");
  
  // This is the instruction that tells the browser to
  // "download" the file
  XLSX.writeFile(wb, 'book.xlsx');
}

document.querySelector('#saveBook').onclick = saveBook;