Javascript - Download CSV as File
Asked Answered
H

4

22

I'm messing with some javascript to download some csv text:

<script>
var data = '"Column One","Column Two","Column Three"';
window.location.href = 'data:text/csv;charset=UTF-8,' + encodeURIComponent(data);
</script>

So far this is working, but as the browser prompts me to save the file, there is no filename, nor extension.

How can I predetermine the name of the file and it's extension, inside the window.location.href ?

Heinie answered 17/1, 2014 at 3:3 Comment(2)
Depending on your target client, you may consider the HTML5 download attribute of <a>.Obscurity
possible duplicate of Export javascript data to CSV file without server interactionTanatanach
T
25
function downloadFile(fileName, urlData) {

    var aLink = document.createElement('a');
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent("click");
    aLink.download = fileName;
    aLink.href = urlData;
    aLink.dispatchEvent(evt);
}

var data = '"Column One","Column Two","Column Three"';
downloadFile('2.csv', 'data:text/csv;charset=UTF-8,' + encodeURIComponent(data));

http://jsfiddle.net/rooseve/7bUG8/

Touching answered 17/1, 2014 at 3:18 Comment(2)
Don't forget to ".remove" the element.Injection
@YevgeniyAfanasyev Can you put more explanation, and reference?Honkytonk
S
19

In my case, it turned out that Excel ignored the charset=UTF-8 part. I found a solution in this post, to force Excel to take into account the UTF-8. So this last line did the trick for me:

downloadFile('2.csv', 'data:text/csv;charset=UTF-8,' + '\uFEFF' + encodeURIComponent(data));
Sumpter answered 21/5, 2014 at 15:0 Comment(2)
Thank you very much, it may not be related to question, but it helped me in my struggle.Injection
This ends up serving the file as UTF-8-DOMHollins
D
9

Updated Andrew's Answer to avoid using a deprecated function.

source: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events#The_old-fashioned_way

//Triggers a download of the given file
//@see https://mcmap.net/q/571265/-javascript-download-csv-as-file
//@see https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events#The_old-fashioned_way
//
//@param fileName {string} - Name of the file to download include file extension
//@param urlData {string} - Encoded URI of the document data
function downloadFile(fileName, urlData) {

    var aLink = document.createElement('a');
    aLink.download = fileName;
    aLink.href = urlData;

    var event = new MouseEvent('click');
    aLink.dispatchEvent(event);
}

var data = '"Column One","Column Two","Column Three"';
downloadFile('2.csv', 'data:text/csv;charset=UTF-8,' + encodeURIComponent(data));
Desberg answered 11/10, 2016 at 17:32 Comment(1)
file is being save with fileUrl(urlData) instead of fileName.Vano
P
-1

In response to the earlier answers, Mozilla Firefox and Google Chrome no longer allow you to redirect the main window to a data URI. To get around this, you can create an iframe element and an a element that will redirect that iframe element to your data URI. Here is a sample of code that will do the trick.

function downloadTable(idTable) {
  function convertData() {
    function convertDataRow(elRow) {
      function convertDataCell(elCell) {
        return elCell.textContent.trim(); // Convert cell contents to plain text
      }
      var $cells = elRow.getElementsByTagName("td"); // Get all cells in this row
      // Convert the NodeList to an array and return an array of plain-text cell contents
      return Array.prototype.slice.call($cells).map(convertDataCell);
    }
    // Get all the rows in the table body
    var $rows = document.getElementById(idTable).querySelectorAll("tbody tr");
    // Convert the NodeList to an array and return an array of arrays with cell contents
    return Array.prototype.slice.call($rows).map(convertDataRow);
  }
  function convertHeaders() {
    function convertHeader(elHeader) {
      return elHeader.textContent.trim(); // Convert header contents to plain text.
    }
    // Get all headers in the table header
    var $headers = document.getElementById(idTable).querySelectorAll("thead th");
    // Convert the NodeList to an array and return an array of header contents.
    return Array.prototype.slice.call($headers).map(convertHeader);
  }
  function convertToCsv(data) {
    function convertCellToCsv(elData) {
      // Escape any quotes before returning the quoted string
      return "\"" + (elData || "").replace(/"/g, "\"\"") + "\"";
    }
    function convertRowToCsv(elRow) {
      // Return a comma-separated string of data values
      return elRow.map(convertCellToCsv).join(",");
    }
    // Return each row on its own line
    return data.map(convertRowToCsv).join("\n");
  }
  var csvToExport = convertToCsv([convertHeaders()].concat(convertData()));
  var dateNow = new Date();
  var timeStamp = (new Date(dateNow - dateNow.getTimezoneOffset() * 60000)) // Local time
    .toISOString() // Convert to ISO 8601 string
    .replace(/[^\d]/g, "-") // Turn anything that isn't a digit into a hyphen
    .replace(/-\d+-$/, ""); // Strip off the milliseconds
  var nameFile = "download-" + timeStamp + ".csv";
  if (navigator.msSaveBlob) { // Are we running this in IE?
    // Yes, we are running this in IE. Use IE-specific functionality.
    var blobExport = new Blob([csvToExport], { type: "text/csv;charset=utf-8," });
    navigator.msSaveBlob(blobExport, nameFile);
  } else {
    // No, we are not running this in IE. Use the iframe/link workaround.
    var urlData = "data:text/csv;charset=utf-8," + encodeURIComponent(csvToExport);
    // Create the iframe element and set up its attributes and styling
    var $iframe = document.createElement("iframe");
    $iframe.setAttribute("name", "iframe_download");
    $iframe.setAttribute("src", "about:blank");
    $iframe.style.visibility = "hidden";
    document.body.appendChild($iframe);
    // Create the a element and set up its attributes and styling.
    var $link = document.createElement("a");
    $link.setAttribute("download", nameFile);
    $link.setAttribute("href", urlData);
    // The target value should equal the iframe's name value.
    $link.setAttribute("target", "iframe_download");
    $link.style.visibility = "hidden";
    document.body.appendChild($link);
    // After the iframe loads, clean up the iframe and a elements.
    $iframe.addEventListener(
      "load",
      function () {
        document.body.removeChild($iframe);
        document.body.removeChild($link);
      }
    );
    $link.click(); // Send a click event to the link
  }
}
<table id="tableDownload" summary="Data to export">
  <thead>
    <tr>
      <th scope="col" style="text-align: left">Last Name</th>
      <th scope="col" style="text-align: left">First Name</th>
      <th scope="col" style="text-align: left">Street Address</th>
      <th scope="col" style="text-align: left">City</th>
      <th scope="col" style="text-align: left">State</th>
      <th scope="col" style="text-align: left">ZIP</th>
      <th scope="col" style="text-align: left">Phone</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Blackburn</td>
      <td>Mollie</td>
      <td>P.O. Box 620, 1873 Aliquet St.</td>
      <td>Waterbury</td>
      <td>CT</td>
      <td>99762</td>
      <td>1-318-946-6734</td>
    </tr>
    <tr>
      <td>Gamble</td>
      <td>Caleb</td>
      <td>8646 Aliquam Rd.</td>
      <td>Sacramento</td>
      <td>CA</td>
      <td>92800</td>
      <td>1-340-761-1459</td>
    </tr>
    <tr>
      <td>Mercer</td>
      <td>Keegan</td>
      <td>P.O. Box 454, 8858 Cursus Rd.</td>
      <td>Glendale</td>
      <td>AZ</td>
      <td>85590</td>
      <td>1-546-775-3600</td>
    </tr>
    <tr>
      <td>Lara</td>
      <td>Ethan</td>
      <td>575-5292 Egestas Rd.</td>
      <td>Denver</td>
      <td>CO</td>
      <td>21083</td>
      <td>1-830-500-3031</td>
    </tr>
    <tr>
      <td>Bennett</td>
      <td>Elmo</td>
      <td>P.O. Box 733, 6784 Magnis Ave</td>
      <td>Frankfort</td>
      <td>KY</td>
      <td>89835</td>
      <td>1-522-310-1841</td>
    </tr>
    <tr>
      <td>Dotson</td>
      <td>Stella</td>
      <td>132-2549 Eu Rd.</td>
      <td>Covington</td>
      <td>KY</td>
      <td>62519</td>
      <td>1-286-790-1404</td>
    </tr>
    <tr>
      <td>Malone</td>
      <td>Helen</td>
      <td>628 Gravida. St.</td>
      <td>Atlanta</td>
      <td>GA</td>
      <td>13271</td>
      <td>1-725-538-6018</td>
    </tr>
    <tr>
      <td>Lowe</td>
      <td>Macon</td>
      <td>Ap #445-9655 Velit Rd.</td>
      <td>Salem</td>
      <td>OR</td>
      <td>66270</td>
      <td>1-709-760-5241</td>
    </tr>
    <tr>
      <td>Haley</td>
      <td>Aileen</td>
      <td>833-1082 Duis Av.</td>
      <td>Southaven</td>
      <td>MS</td>
      <td>27019</td>
      <td>1-445-457-5467</td>
    </tr>
    <tr>
      <td>Riley</td>
      <td>Wade</td>
      <td>8270 Aliquam St.</td>
      <td>Grand Rapids</td>
      <td>MI</td>
      <td>95408</td>
      <td>1-254-595-8386</td>
    </tr>
  </tbody>
</table>
<button type="button" id="btnDownload" onclick="downloadTable('tableDownload')">Download Table</button>

Note that, if you decide to use jQuery, you still need to use the native click function—$("a#linkDownload")[0].click() instead of simply $("a#linkDownload").click().

Plumbic answered 13/5, 2019 at 14:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.