简体   繁体   English

以.xls格式文件下载数据

[英]download data as .xls format file

I need to download list data as .xls file.My controller code is follows. 我需要将列表数据下载为.xls文件。我的控制器代码如下。

     [HttpGet]
        public void AttendeeListToExport()
        {
            string campaign_id = string.Empty;
            campaign_id = ((MemberProfile)HttpContext.Current.Profile).HOWCampaignID;
            AutoCRM.Services.HOW.Attendee.Manage manage = new AutoCRM.Services.HOW.Attendee.Manage();
            DataSet lst = manage.AttendeeListToExport(campaign_id);
            if (lst != null)
            {
                if (lst.Tables[0].Rows.Count > 0)
                {
                    DataTable dt = lst.Tables[0];
                    // Export all the details to Excel
                    string filename = campaign_id + "_" + DateTime.Now.ToString("ddMMyyyy") + ".xls";
                    Export objExport = new Export();
                    objExport.ExportDetails(dt, Export.ExportFormat.Excel, filename);
                }
            }
        }

js code js代码

$('#exportToExcel').on("click", function () {
        alert('hi');
        $.ajax({
            url: "/api/Attendee/AttendeeListToExport",
            async: true,
            cache: false,
            success: function (result) {
                alert(result);
            }
        });
    });

code executing correctly but file not downloading 代码正确执行但文件未下载

You can download file through javascript in following both ways : 您可以通过以下两种方式通过javascript下载文件:

Using HiddenIFrame : 使用HiddenIFrame:

var downloadURL = function downloadURL(url) {
    var iframe;
    var hiddenIFrameID = 'hiddenDownloader';
    iframe = document.getElementById(hiddenIFrameID);
    if (iframe === null) {
        iframe = document.createElement('iframe');  
        iframe.id = hiddenIFrameID;
        iframe.style.display = 'none';
        document.body.appendChild(iframe);
    }
    iframe.src = url;   
}

Using Jquery : 使用Jquery:

$('a').click(function(e) {
    e.preventDefault();  //stop the browser from following
    window.location.href = 'uploads/file.doc';
});

<a href="no-script.html">Download now!</a>

You can't download files using ajax. 您无法使用ajax下载文件。 You have to use a hidden iframe or link directly to the file. 您必须使用隐藏的iframe或直接链接到该文件。

If your Controller action returned a FileResult, you could download this from your javascript function like this: 如果您的Controller操作返回了FileResult,您可以从您的javascript函数中下载,如下所示:

$('#exportToExcel').on("click", function () {
    window.open("/api/Attendee/AttendeeListToExport", "_blank");
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM