我有问题要下载使用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