【问题标题】:Laravel Excel using with Ajax is not working properly与 Ajax 一起使用的 Laravel Excel 无法正常工作
【发布时间】:2016-02-13 09:10:54
【问题描述】:

我有一个包含很多搜索元素的搜索,然后在搜索结果中我有一个打印按钮,再次需要提交带有许多其他数据的搜索表单以首先找到记录,然后将其打印到 Excel。为此,我使用 Ajax 提交表单并使用 laravel excel 编写,但现在它不适用于 xlsx,并且 xls 有问题。当.xls文件被下载时它的内容是这样的��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������。下面是我的代码:

<script>
function generateReport(printType,printRange) {
        $.ajaxSetup({
            header:$('meta[name="_token"]').attr('content')
        })

        var url = '/auditLog/search/printReport';
        var params = $('#auditSearchForm').serialize()+'&printType=' + printType + '&printRange=' + printRange;

        $.ajax({
            type: "POST",
            url: url,
            data: params,
            success: function (response, status, xhr) {
                // check for a filename
                var filename = "";
                var disposition = xhr.getResponseHeader('Content-Disposition');
                if (disposition && disposition.indexOf('attachment') !== -1) {
                    var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                    var matches = filenameRegex.exec(disposition);
                    if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
                }

                var type = xhr.getResponseHeader('Content-Type');
                var blob = new Blob([response], { type: type });

                if (typeof window.navigator.msSaveBlob !== 'undefined') {
                    // IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
                    window.navigator.msSaveBlob(blob, filename);
                } else {
                    var URL = window.URL || window.webkitURL;
                    var downloadUrl = URL.createObjectURL(blob);

                    if (filename) {
                        // use HTML5 a[download] attribute to specify filename
                        var a = document.createElement("a");
                        // safari doesn't support this yet
                        if (typeof a.download === 'undefined') {
                            window.location = downloadUrl;
                        } else {
                            a.href = downloadUrl;
                            a.download = filename;
                            document.body.appendChild(a);
                            a.click();
                        }
                    } else {
                        window.location = downloadUrl;
                    }

                    setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
                }

            }
        });
    }

</script>

还有我的控制器

public function generateReport()
{
    $result = $this->searchRequest->getDetails();
    //dd($result);
    //$user = Auth::user();
    Excel::create('foo', function($file) {
        $file->sheet('bar', function($sheet) {
            $sheet->setTitle('Hi');
        });
    })->download('xls');
}

任何帮助谢谢。

【问题讨论】:

  • 您知道响应是 BIFF 格式 Excel 文件的二进制流输出吗?问题是 Ajax 响应处理程序不知道如何处理它......使用文件下载链接比 ajax 请求更容易,因为这样您就可以让浏览器处理基于响应在响应标头上
  • @MarkBarker 但是通过链接我如何提交表单而不刷新页面?
  • 为什么不试试呢.....因为 Excel 文件的响应标头与 html 响应的响应标头不同,浏览器的响应也不同
  • @MarkBaker 但是我在表单上有另一个按钮,用于提交表单以进行搜索并显示结果,所以现在我如何使用另一个按钮在另一个功能中提交相同的表单以进行打印目的?
  • 我说的是链接 (&lt;a href="..."&gt;),而不是按钮(尽管您可以根据需要使链接看起来像按钮)

标签: javascript ajax laravel phpexcel laravel-excel


【解决方案1】:

这可能对你有帮助

 $(function() {
        $('#your_div').on('click', '#print', function (e) {
            var reportRange = $('#report_range').val();
            downloadReport($(this).attr('printType'),reportRange);
            e.preventDefault();
        });
    });


    function downloadReport(printType,printRange){
        var http = new XMLHttpRequest();
        http.responseType = 'blob';

        var header;
        var blob;
        var url = '/auditLog/search/printReport';
        var params = $('#auditSearchForm').serialize()+'&printType=' + printType + '&printRange=' + printRange;
        http.open("POST", url, true);

        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

        http.onreadystatechange = function() {//Call a function when the state changes.
            if(http.readyState == 4 && http.status == 200) {
                var filename = "";
                var disposition = http.getResponseHeader('Content-Disposition');
                if (disposition && disposition.indexOf('attachment') !== -1) {
                    var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                    var matches = filenameRegex.exec(disposition);
                    if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
                }
                var type = http.getResponseHeader('Content-Type');
                blob = new Blob([http.response], { type: type ,endings:'native'});
                var URL = window.URL || window.webkitURL;
                var downloadUrl = URL.createObjectURL(blob);
                var a = document.createElement("a");
                a.href = downloadUrl;
                a.download = filename;
                document.body.appendChild(a);
                a.click();
            }
        }
        http.send(params);
    }

【讨论】:

  • @paranoid 很高兴为您提供帮助。
猜你喜欢
  • 2017-11-21
  • 2018-12-03
  • 1970-01-01
  • 1970-01-01
  • 2013-10-08
  • 1970-01-01
  • 2021-08-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多