Flask网站无法将数据导出到Excel文件,尽管没有错误。

huangapple go评论80阅读模式
英文:

Why does my Flask website fail to export data to an Excel file, despite no errors?

问题

The issue you're facing with your Flask website's Excel export functionality seems to be related to how the response is being handled on the client side. While you're getting a 200 response from the server, the file is not being downloaded. Here are some common reasons for this issue:

  1. Response Headers: Make sure that the response headers, specifically the Content-Disposition header, are correctly set. It should specify the filename and indicate that it's an attachment. Your code appears to set this header correctly.

  2. Client-Side Handling: Check how the client-side JavaScript is handling the response. Ensure that it's correctly processing the response and triggering a download. The JavaScript code you've provided looks fine, but you might want to double-check if there are any errors in the browser's console that could provide more information.

  3. AJAX Configuration: Verify that the AJAX request configuration is correct, especially the dataType option. In your case, since you are expecting a binary file (Excel), you should set dataType to 'blob' or simply remove it to let jQuery handle it automatically.

Here's an updated AJAX request without specifying dataType:

$.ajax({
    type: 'POST',
    url: '/export',
    data: JSON.stringify(selectedRows),
    contentType: 'application/json',
    success: function (response) {
        // Trigger a download using Blob and createObjectURL
        var blob = new Blob([response]);
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = 'selected_rows.xlsx';
        link.click();
    },
    error: function (xhr, status, error) {
        console.error('Export error:', error);
    }
});

Make sure to also include proper error handling on the client-side to handle any issues that might arise during the download.

By verifying these aspects and making sure the client-side JavaScript correctly processes the binary response, you should be able to resolve the issue and allow users to download the Excel file.

英文:

I have developed a simple python Flask website where my goal is users can fill a form and then be able to view their previous inputs in a html table and be able to choose and export some rows of the table in a excel file. Although the site is working fine in all other aspects (data are correctly being stored in the database, they also display fine in a table format etc), the export to an excel file can't seem to work...

The part of my html code for the page that tries to export the html table to an excel is the following :

      <button id="exportButton" class="btn btn-primary">Export to Excel</button>
    <script>
      $(document).ready(function () {
        $('#projectTable').DataTable();

        $('#exportButton').click(function () {
          var selectedRows = [];
          $('.row-checkbox:checked').each(function () {
            var rowData = $(this).closest('tr').find('td').map(function () {
              return $(this).text();
            }).get();
            selectedRows.push(rowData);
          });

          // Send selectedRows to the server for export
          $.ajax({
            type: 'POST',
            url: '/export',
            data: JSON.stringify(selectedRows),
            contentType: 'application/json',
            success: function (response) {
              // Handle the server's response, if needed
              // For example, you can show a success message or trigger a file download
              console.log('Export successful!');
            },
            error: function (xhr, status, error) {
              // Handle errors, if any
              console.error('Export error:', error);
            }
          });
        });
      });
    </script>
  </body>
</html>

while my /export endpoint which is used in the ajax request is :

@views.route('/export', methods=['POST'])
@login_required
def export():
    selected_rows = request.get_json()  # Get the selected rows' data from the request

    # Create a DataFrame from the selected rows' data
    df = pd.DataFrame(selected_rows, columns=['header1', 'header2', 'header3', 'header4',
                                              'header5', 'header6',
                                              'header7',
                                              'header8'])

    # Generate an Excel file from the DataFrame
    excel_file = io.BytesIO()
    df.to_excel(excel_file, index=False)
    excel_file.seek(0)  # Move the file pointer to the beginning of the file
    # Prepare the response headers
    headers = {
        'Content-Disposition': 'attachment; filename=selected_rows.xlsx',
        'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    }

    # Return the Excel file contents as the response
    return Response(excel_file, headers=headers)

Although i get a 200 response back from the server ('127.0.0.1 - - [24/May/2023 19:21:00] "POST /export HTTP/1.1" 200 -'), no excel file is being downloaded (exported) to the client. Why is that?

答案1

得分: 0

我最终摆脱了/export端点,并仅使用JavaScript代码修复了问题。对于任何感兴趣的人,这是我使用的代码:

<script src="https://unpkg.com/xlsx/dist/xlsx.full.min.js"></script>
<script type="text/javascript">
  function getSelectedRows() {
    const checkboxes = document.querySelectorAll(".row-checkbox");
    const selectedRows = [];

    checkboxes.forEach(function (checkbox) {
      if (checkbox.checked) {
        const row = checkbox.closest("tr");
        selectedRows.push(row);
      }
    });

    return selectedRows;
  }

  function exportReportToExcel() {
    const selectedRows = getSelectedRows();

    if (selectedRows.length === 0) {
      alert("未选择行。请至少选择一行。");
      return;
    }

    const table = document.createElement("table");
    const tableBody = document.createElement("tbody");

    selectedRows.forEach(function (row) {
      tableBody.appendChild(row.cloneNode(true));
    });

    table.appendChild(tableBody);

    const wb = XLSX.utils.table_to_book(table, { sheet: "Sheet 1" });
    XLSX.writeFile(wb, "file.xlsx");
  }
</script>
英文:

I eventually got rid of the /export endpoint and fixed the issue with solely javascript code. For anyone interested, this is the code i used :

    &lt;script src=&quot;https://unpkg.com/xlsx/dist/xlsx.full.min.js&quot;&gt;&lt;/script&gt;
    &lt;script type=&quot;text/javascript&quot;&gt;
      function getSelectedRows() {
        const checkboxes = document.querySelectorAll(&quot;.row-checkbox&quot;);
        const selectedRows = [];
    
        checkboxes.forEach(function (checkbox) {
          if (checkbox.checked) {
            const row = checkbox.closest(&quot;tr&quot;);
            selectedRows.push(row);
          }
        });
    
        return selectedRows;
      }
    
      function exportReportToExcel() {
        const selectedRows = getSelectedRows();
    
        if (selectedRows.length === 0) {
          alert(&quot;No rows selected. Please select at least one row.&quot;);
          return;
        }
    
        const table = document.createElement(&quot;table&quot;);
        const tableBody = document.createElement(&quot;tbody&quot;);
    
        selectedRows.forEach(function (row) {
          tableBody.appendChild(row.cloneNode(true));
        });
    
        table.appendChild(tableBody);
    
        const wb = XLSX.utils.table_to_book(table, { sheet: &quot;Sheet 1&quot; });
        XLSX.writeFile(wb, &quot;file.xlsx&quot;);
      }
    &lt;/script&gt;

huangapple
  • 本文由 发表于 2023年5月25日 00:35:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76325709.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定