Javascript - Download CSV as File

后端 未结 4 736
日久生厌
日久生厌 2020-12-28 17:54

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



        
4条回答
  •  清酒与你
    2020-12-28 18:29

    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
      }
    }
    Last Name First Name Street Address City State ZIP Phone
    Blackburn Mollie P.O. Box 620, 1873 Aliquet St. Waterbury CT 99762 1-318-946-6734
    Gamble Caleb 8646 Aliquam Rd. Sacramento CA 92800 1-340-761-1459
    Mercer Keegan P.O. Box 454, 8858 Cursus Rd. Glendale AZ 85590 1-546-775-3600
    Lara Ethan 575-5292 Egestas Rd. Denver CO 21083 1-830-500-3031
    Bennett Elmo P.O. Box 733, 6784 Magnis Ave Frankfort KY 89835 1-522-310-1841
    Dotson Stella 132-2549 Eu Rd. Covington KY 62519 1-286-790-1404
    Malone Helen 628 Gravida. St. Atlanta GA 13271 1-725-538-6018
    Lowe Macon Ap #445-9655 Velit Rd. Salem OR 66270 1-709-760-5241
    Haley Aileen 833-1082 Duis Av. Southaven MS 27019 1-445-457-5467
    Riley Wade 8270 Aliquam St. Grand Rapids MI 95408 1-254-595-8386

    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().

提交回复
热议问题