Click here to Skip to main content
15,907,906 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I want to export data in excel in server side and download that excel file to client side on button click . I created a web service method and made an ajax call from jQuery. In the web service, I was able to create excel and store it to the server side module but I am unable to download the file on client side. I've no idea how to do it? Can any one help me? I've attached code what I've done.

What I have tried:

Web service code

C#
[WebMethod]
    [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
    public string ExportReport(int SelectedValue, string KeyValue, string DdlCltVal, string DdlLocVal, string DdlstfVal, int BtnID, DateTime StrDate, DateTime EndDate, int currentPage)
    {
        try
        {
            CommonFunction obj = new CommonFunction();
            DataTable dt = new DataTable();
            string rhead = "";
            if (SelectedValue != 0 && KeyValue == "0" && DdlCltVal == "0" && DdlLocVal == "0" && DdlstfVal == "0")
            {
                CourierReportController objCtr = new CourierReportController();
                dt = ListToDataTable.ToDataTable(objCtr.GetDailyReport(0, 10, SelectedValue));
                rhead = "Daily";
            }
            StringBuilder sb = new StringBuilder();
            foreach (DataColumn column in dt.Columns)
            {
                sb.Append(column.ColumnName + "\t");
            }
            sb.Append("\n");
            foreach (DataRow row in dt.Rows)
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    sb.Append(row[i].ToString() + "\t");
                }
                sb.Append("\n");
            }
            string strFilename = "CourierReport_" + rhead + ".xls";
            string strUploadPath = Server.MapPath("userexports").ToString();
            File.WriteAllText(strUploadPath + "\\" + strFilename, sb.ToString());
            return strFilename;         
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }


Client side code:

JavaScript
$('#btnExport').click(function (e) {
 var data= JSON2.stringify({
                    SelectedValue: selectedValue,
                    KeyValue: KeyValue,
                    DdlCltVal: ddlCltVal,
                    DdlLocVal: ddlCltVal,                    
                    DdlstfVal: ddlstfVal,
                    BtnID:btnid,                    
                    StrDate: strDate,
                    EndDate: endDate,
                    currentPage: currentPage
                });
            $.ajax({
                    contentType:  "application/json; charset=utf-8",
                    type: 'POST',                       url:'http://localhost:8043/Modules/CourierReport/services/CourierReport.asmx/ExportReport',
                    dataType: 'json',
                    data:data,
                    success: function(result){
                    alert (result.d);
                    //should i do any thing here?
                    },
                    error: function(error){
                    alert("error");
                    }
                });
                    return false;
});
Posted
Updated 3-Mar-16 2:17am
v2

You won't be able to use code like that, javascript can't save files to the local drive, and you're just returning a filename that exists on the server. Google for how to download a file to the client and you'll find examples

Downloading a File with a Save As Dialog in ASP.NET - Rick Strahl's Web Log[^]

As suggested already, you need to direct the client to a link that has your download code, like

<a href="/KB/answers/MyDownloadPage.aspx" target="_blank">Download</a>

with the MyDownloadPage sending the file as per the code in the link.
 
Share this answer
 
Once you have received the URL for the file, you can make use of window.location. Set this value to file URL and you should be able to download the file.

Make sure that there something on server side that is doing periodic clean up of unused/outdated files. Also ensure that file names are unique and proper access is given for the location where files are stored on server.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900