关闭

js导出表格数据

标签: ajax下载outputtablecsvexcel
252人阅读 评论(0) 收藏 举报
分类:

考虑到浏览器兼容性问题,采用原生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表单
            form.attr("style","display:none");
            form.attr("target","");
            form.attr("method","post");
            form.attr("action","/api/data/exportCSV");
            var input1=$("<input>");
            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";');
    }


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:2953次
    • 积分:87
    • 等级:
    • 排名:千里之外
    • 原创:6篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档