js导出表格数据

考虑到浏览器兼容性问题,采用原生js和后台交互下载网页数据

js:

var table = $('.table-panel table');
            // Header
            var tdData ="";
            $(table).find('thead').find('tr').each(function() {
                $(this).find('th').each(function() {
                    tdData += '"' + $(this).text() + '",';
                });
                tdData = $.trim(tdData).substring(0, tdData.length -1);
                tdData += "\r\n";
            });

            // Row vs Column
            $(table).find('tbody').find('tr').each(function() {
                $(this).find('td').each(function(index,data) {
                    tdData += '"'+ $(this).text() + '",';
                });
                tdData = $.trim(tdData).substring(0, tdData.length -1);
                tdData += "\r\n";
            });
            
            var form=$("
");//定义一个form表单 form.attr("style","display:none"); form.attr("target",""); form.attr("method","post"); form.attr("action","/api/data/exportCSV"); var input1=$(""); input1.attr("type","hidden"); input1.attr("name","exportData"); input1.attr("value",tdData); $("body").append(form);//将表单放置在web中 form.append(input1); form.submit();//表单提交

PHP:

public function exportCSV() {
        $exportData = $_POST['exportData'];
        $exportData = iconv("UTF-8", "GB18030//IGNORE", $exportData);
        // open raw memory as file so no temp files needed, you might run out of memory though
        $f = fopen('php://output', 'w');
        fwrite($f, $exportData);
        // tell the browser it's going to be a csv file
        header('Content-Type: application/csv');
        // tell the browser we want to save it instead of displaying it
        header('Content-Disposition: attachment; filename="exportData.csv";');
    }


你可能感兴趣的:(前端)