我有問題要下載使用jQuery的Excel文件。我已經在一些論壇上讀到,使用ajax這是不可能的,並且在一些他們說你可以實現這個結果發送到iframe。到目前爲止,我還沒有能夠解決我的問題。如何使用byte []中的webmethod從javascript或jquery下載文件?
技術細節: 我使用一些參數生成對數據庫的查詢,webservice執行此查詢並返回在openxml中生成的excel文件並返回字節。 我正在使用asp.net 4.0。 如果我使用常規webcontrols和ajax文件下載沒有問題,如果在更新面板中,我將觸發器設置爲asp:postbacktrigger到按鈕控件。
我想用jqueryUi控件和jquery實現相同的結果。
在服務器側I有兩種方法:
ExportToExcel: 此方法接收參數來調用web服務休息,返回excelfile。
SendExcelFileByBytes 這一個是返回請求中的文件的方法。
下面是C#代碼:
[WebMethod]
public static void ExportToExcel(List<int> status, List<Guid> companyId, List<DateTime> dateFrom, List<DateTime> dateTo, bool isGroupedByStore)
{
ReconciliationModule server = new ReconciliationModule(ConfigurationManager.AppSettings["serviceNamespace"], ConfigurationManager.AppSettings["ACSHostUrl"], ConfigurationManager.AppSettings["scopeAddress"]);
SummaryReport summaryReport = new SummaryReport();
List<Tuple<Guid, DateTime, DateTime, int>> parameters = new List<Tuple<Guid, DateTime, DateTime, int>>();
for (int i = 0; i < dateTo.Count; i++)
{
parameters.Add(new Tuple<Guid, DateTime, DateTime, int>(
companyId[i],
dateFrom[i],
dateTo[i],
status[i]
));
}
byte[] x = server.GetSummaryReportInExcel(ConfigurationManager.AppSettings["userName"], ConfigurationManager.AppSettings["pwdOrSymmetricKey"], bool.Parse(ConfigurationManager.AppSettings["isSymmetricKey"]), isGroupedByStore, parameters);
SendExcelFileByBytes(x);
}
private static void SendExcelFileByBytes(byte[] x)
{
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=\"SummaryReport.xlsx\"");
System.Web.HttpContext.Current.Response.AddHeader("Content-Type", "application/force-download");
System.Web.HttpContext.Current.Response.AddHeader("Content-Type", "application/download");
//System.Web.HttpContext.Current.Response.AddHeader("Content-Transfer-Encoding", "binary");
System.Web.HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";//excel file
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.BinaryWrite(x);
//System.Web.HttpContext.Current.Response.Close();
System.Web.HttpContext.Current.Response.Flush();
System.Web.HttpContext.Current.Response.End();
}
對於JScript的我callAjaxFunction失敗,並在responseText的結果返回200 OK消息。所以在執行失敗的函數時,我在表中顯示了responseText。 如果有人可以幫助我以更好的方式做到這一點,將不勝感激。 這裏是JScript代碼:
//Executes Ajax Calls using json as data type
function callAjax(callType, urlAddress, dataToSend, fnSucceeded, fnFailed) {
$.ajax({
type: callType,
url: urlAddress,
contentType: "application/json; charset=utf-8",
data: dataToSend,
dataType: "json",
success: fnSucceeded,
error: fnFailed
});
}
//TODO: This function is the one i need to correct
function getSummaryReportInExcel() {
ShowLoader('#reconciliation');
var isGroupedByStore = new Boolean($('#CompanyTypes :checkbox').attr('checked'));
var stat = getStatus();
var status = new Array();
var companyId = new Array();
var dateFrom = new Array();
var dateTo = new Array();
var companiesToSearch = $('#CompanyConfigurations :checkbox:checked');
//populating the parameters
$(companiesToSearch).each(function (i, currentCompany) {
status.push(stat);
companyId.push($(currentCompany).select('checkbox').attr('value'));
dateFrom.push($(currentCompany).parents().find('td:eq(2) :input').attr('value'));
dateTo.push($(currentCompany).parents().find('td:eq(3) :input').attr('value'));
});
var data = "{ status : " + JSON.stringify(status) + ", companyId : " + JSON.stringify(companyId) + ", dateFrom : " + JSON.stringify(dateFrom) + ", dateTo : " + JSON.stringify(dateTo) + ", isGroupedByStore : " + isGroupedByStore + " }";
alert(data);
callAjax(
"POST", "UIJquery.aspx/ExportToExcel",
data,
//is not entering here
function() {
alert('Hola' + result.toString());
//header.
HideLoader();
},
//AjaxFailed
function (result) {
//alert(concatObject(result));
$('#SearchResults').append(concatObject(result));
//var iFrame = "<iframe src=" + result.responseText + "></iframe>";
$('#IResults').html(result.responseText);
//window.open(result.responseText, 'Download');
HideLoader();
//alert(concatObject(result));
}
);
}
以下是我在開發者工具看到谷歌瀏覽器
HeadersPreviewResponseTiming
Request URL:http://localhost:53144/UIJquery.aspx/ExportToExcel
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:application/json, text/javascript, */*; q=0.01
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:216
Content-Type:application/json; charset=UTF-8
Host:localhost:53144
Origin:http://localhost:53144
Referer:http://localhost:53144/UIJQuery.aspx
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.83 Safari/535.11
X-Requested-With:XMLHttpRequest
Request Payload
{ status : [15,15], companyId : ["15afbacb-5c0c-4402-a5af-0f5a53221bbb","041d6a48-35ca-4d55-97ec-4fd5f4bdd11f"], dateFrom : ["11/06/2011","11/06/2011"], dateTo : ["11/12/2011","11/12/2011"], isGroupedByStore : true }
Response Headersview source
Cache-Control:private, max-age=0
Connection:Close
Content-Disposition:attachment; filename="SummaryReport.xlsx"
Content-Type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Date:Wed, 28 Mar 2012 18:22:32 GMT
Server:ASP.NET Development Server/10.0.0.0
Transfer-Encoding:chunked
X-AspNet-Version:4.0.30319
任何建議或更好的方法來做到這一點讓我知道感謝。
請告訴我GE的點在jQuery中使用二進制文件?只需構建將導致文件下載並將brwoser發送給它的url(window.location)。 – poncha 2012-03-28 18:48:20
你能舉個例子嗎?我是新來的網站謝謝。 – user1298857 2012-03-28 19:37:12
在你的CallAjax中,你告訴jQuery希望返回一個JSON字符串,當它從你的web服務獲取二進制文件時會失敗。 jQuery.ajax中沒有「二進制」或「字節」數據類型,最接近的是「文本」,這對於二進制輸出不會很好。 – Rob 2012-03-28 19:50:29