我想在服务器端的excel中导出数据,并在点击按钮时将该excel文件下载到客户端。我创建了一个Web服务方法,并从jQuery进行了ajax调用。在webservice中,我能够创建excel并将其存储到服务器端模块,但我无法在客户端下载该文件。我不知道怎么做?谁能帮我?怎么做。 我附上了我已经完成的代码。
//网络服务代码
[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;
}
}
//客户端代码
$('#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;
});
答案 0 :(得分:0)
我不知道使用ajax调用创建和下载excel但是我建议你在服务器的文件系统中保存excel并使用window.location
下载它
示例代码将是(由于时间限制不能修改您的代码,但我很乐意以后再做)
jquery的:
$.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){
window.location("saved file path with come here");
},
error: function(error){
alert("error");
}
});
asmx文件代码:
[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public string ExportReport()
{
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
gvFiles.RenderControl(htw);
string renderedGridView = sw.ToString();
System.IO.File.WriteAllText(@"Path on server to save file", renderedGridView);
}