首页 > 解决方案 > 当我尝试在 csv 中导出超过 1000 条记录时出现页面无响应错误?

问题描述

我已经构建了我的应用程序。我有 2000 多条记录作为报告获取,这些记录在前端可见。当我尝试将数据导出到 csv 时,我的页面将卡住或显示页面无响应错误。在任何一种情况下都会下载 CSV,但这个问题很烦人。

如何在代码级别处理它?

这是我的代码的一部分

$filename = $filename.''.time().'.csv';
$file = fopen($reportDir.'/'.$filename,"w");
fwrite($file,$transContent);
fclose($file);

我也试过fputcsv了。我也试过

ini_set('memory_limit', '-1');
ini_set('opcache.enable', '0');
ini_set('max_execution_time', '0');

我也尝试禁用Opcache但没有任何工作?

标签: javascriptphpdatabasememory

解决方案


使用以下代码。祝你好运

function download_csv(csv, filename) {
    var csvFile;
    var downloadLink;

    // CSV FILE
    csvFile = new Blob([csv], {type: "text/csv"});

    // Download link
    downloadLink = document.createElement("a");

    // File name
    downloadLink.download = filename;

    // We have to create a link to the file
    downloadLink.href = window.URL.createObjectURL(csvFile);

    // Make sure that the link is not displayed
    downloadLink.style.display = "none";

    // Add the link to your DOM
    document.body.appendChild(downloadLink);

    // Lanzamos
    downloadLink.click();
}

function export_table_to_csv(html, filename) {
    var csv = [];
    var rows = document.querySelectorAll("table tr");
    
    for (var i = 0; i < rows.length; i++) {
        var row = [], cols = rows[i].querySelectorAll("td, th");
        
        for (var j = 0; j < cols.length; j++) 
            row.push(cols[j].innerText);
        
        csv.push(row.join(","));        
    }

    // Download CSV
    download_csv(csv.join("\n"), filename);
}

document.querySelector("button").addEventListener("click", function () {
    var html = document.querySelector("table").outerHTML;
    export_table_to_csv(html, "table.csv");
});
* {
    color: #2b2b2b;
    font-family: "Roboto Condensed";
}

th {
    text-align: left;
    color: #4679bd;
}

tbody > tr:nth-of-type(even) {
    background-color: #daeaff;
}

button {
    cursor: pointer;
    margin-top: 1rem;
}
<table>
    <tr><th>Name</th><th>Age</th></tr>
    <tr><td>A</td><td>26</td></tr>
    <tr><td>B</td><td>19</td></tr>
    <tr><td>C</td><td>32</td></tr>
</table>
<button>Export HTML table to CSV file</button>


推荐阅读