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
[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:
$('#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);
},
error: function(error){
alert("error");
}
});
return false;
});