Home>

When I select the button, I want to download it as CSV, but it doesn't work.
I think there is no problem with the value, but the contents of the downloaded file are not in CSV format.
Can you point out what is wrong?

<html>
<head>
<title></title>
<meta charset = "utf-8">
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<form>
<table>
    <tr>
        <td>A</td><td>B</td><td>C</td><td>D</td><td><input type = "checkbox" name = "11" value = " Apple, 1,200 "></td>
    </tr>
    <tr>
        <td>a</td><td>b</td><td>c</td><td>d</td><td><input type = "checkbox" name = "11" value = " Melon, 2,4000 "></td>
    </tr>
    <tr>
        <td>1</td><td>2</td><td>3</td><td>4</td><td><input type = "checkbox" name = "11" value = " Banana, 4,500 "></td>
    </tr>
</table>
</form>
<p>CSV Expoert</p>
<script>
$(function () {
$('. btn'). on ('click', function () {
var text = '';
/ * Get value * /
$("[name = 11]: checked"). each (function () {
    text = text + $(this) .val () + ',';
});
    / * Array * /
    var array_data = [text];
    / * The following array will work * /
    // var array_data = [['apple', 1,200], ['melon', 2,4000], ['banana', 4,500]];
    / * BOM ready * /
    var bom = new Uint8Array ([0xEF, 0xBB, 0xBF]);
    / * Prepare CSV * /
    var csv_data = array_data.map (function (l) {return l.join (',')}). join ('\ r \ n');
    var blob = new Blob ([bom, csv_data], {type: 'text/csv'});
    var url = (window.URL || window.webkitURL) .createObjectURL (blob);
    var a = document.getElementById ('downloader');
    a.download = 'data.csv';
    a.href = url;
    / * Click to download * /
    $('# downloader') [0] .click ();
  });
});
</script>
</body>
</html>
  • Answer # 1

    The following parts

    /* array * /
        var array_data = [text];
        / * The following array will work * /
        // var array_data = [['apple', 1,200], ['melon', 2,4000], ['banana', 4,500]];


    As you can see fromconsle.loghere,textisapple, 1,200, melon, 2,4000, banana, 4,500,(String), array_data is["apple, 1,200, melon, 2,4000, banana, 4,500,"](naturally an array with only one string).
    You can see that the format is different from the successful array.
    If you want to make use of the subsequent processing as it is, make sure that it is in the same format as a successful array.