Генерация файла CSV из введенных данных HTML - PullRequest
1 голос
/ 15 мая 2019

Я пытался передать введенные пользователем данные в формате HTML в CSV-файл на локальном диске. Но, похоже, в этом есть какая-то ошибка.

Я попробовал приведенный ниже код, даже если он скопирован из других источников.

    <html>
  <head>
  <script language="javascript">
    function WriteToFile(passForm) {
      var fso = new ActiveXObject("Scripting.FileSystemObject");
      var fileLoc = "C:\\sample.txt";
      var file = OpenTextFile(fileLoc,2,true,0);
     file.write("File handling in Javascript");
      file.Close();
      alert('File created successfully at location: ' + fileLoc);
     }
  </script>
  </head>
  <body>
  <p>create a csv file with following details -</p>
  <form>
    Type your first name: <input type="text" name="FirstName" size="20"><br>
    Type your last name: <input type="text" name="LastName" size="20"><br>
    <input type="button" value="submit" onclick="WriteToFile(this.form)">
  </form>
  </body>
</html>
</br></br></html>

CSV-файл не создается и не может получить ошибку в HTML.

1 Ответ

2 голосов
/ 15 мая 2019

Вы не использовали переменную fso для вызова OpenTextFile, вы также должны иметь в виду, что IE имеет разрешения на запись в путь

Это должно работать для вас:

<html>
<head>
    <script language="javascript">
        function WriteToFile(passForm) {
            var fso = new ActiveXObject("Scripting.FileSystemObject");
            var fileLoc = "C:\\Users\\yourUser\\sample.csv";
            var file = fso.OpenTextFile(fileLoc,2,true,0);
            file.write("File handling in Javascript");
            file.Close();
            alert('File created successfully at location: ' + fileLoc);
        }
    </script>
</head>
<body>
    <p>create a csv file with following details -</p>
    <form>
        Type your first name: <input type="text" name="FirstName" size="20"><br>
        Type your last name: <input type="text" name="LastName" size="20"><br>
        <input type="button" value="submit" onclick="WriteToFile(this.form)">
    </form>
</body>
</html>

Вы также можете использовать это решение, которое работает для нескольких браузеров:

<html>
<head>
    <script language="javascript">
        function downloadCSV(form) {
            const content = 'Write your csv content here!!';
            const mimeType = 'text/csv;encoding:utf-8';
            const fileName = 'download.csv';
            const a = document.createElement('a');

            if (navigator.msSaveBlob) { // IE10
                navigator.msSaveBlob(new Blob([content], {
                    type: mimeType
                }), fileName);
            } else if (URL && 'download' in a) { //html5 A[download]
                a.href = URL.createObjectURL(new Blob([content], {
                    type: mimeType
                }));
                a.setAttribute('download', fileName);
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
            } else {
                location.href = 'data:application/octet-stream,' + encodeURIComponent(content); // only this mime type is supported
            }
        }
    </script>
</head>
<body>
    <p>create a csv file with following details -</p>
    <form>
        Type your first name: <input type="text" name="FirstName" size="20"><br>
        Type your last name: <input type="text" name="LastName" size="20"><br>
        <input type="button" value="submit" onclick="downloadCSV(this.form)">
    </form>
</body>
</html>
...