我有经典的asp.net网站。我有一个数据网格,我想导出为excel表。该站点使用Windows身份验证。
我选择code while googling寻求解决方案。以下是我在FF和Chrome中遇到的问题,需要帮助来纠正它:
有时文件下载会毫无问题地发生,但是如果我让窗口处于非活动状态一分钟左右然后再试一次,那么我会发现页面未找到问题,或者浏览器会继续请求登录(陷入困境)。
有时候点击导出按钮时,FF只会继续显示Windows登录弹出窗口,就像它被卡在循环中一样。
按钮:
<asp:Button ID="cmdExportDataGridToExcel_Click" runat="server" OnClick="cmdExportToExcel_Click" CssClass="StandardText" Text="Export to Excel" Width="120px" Height="33px"></asp:Button>
代码:
protected void cmdExportDataGridToExcel_Click(object sender, System.EventArgs e)
{
//export to excel
Response.Clear();
var userName = CommonMethods.GetUserId();
var fileName = string.Format("ScheduledOrdersReport-{0}-{1:yyyyMMddhhmmsstt}.xls", userName, DateTime.Now);
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
hsGrid.AllowPaging = false;
this.BindHSGrid(false, string.Empty);
//this.EnableViewState = false;
var oStringWriter = new StringWriter();
var oHtmlTextWriter = new HtmlTextWriter(oStringWriter);
this.ClearControls(hsGrid);
hsGrid.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
}
private void ClearControls(Control control)
{
for (int i = control.Controls.Count - 1; i >= 0; i--)
{
ClearControls(control.Controls[i]);
}
if (!(control is TableCell))
{
if (control.GetType().GetProperty("SelectedItem") != null)
{
LiteralControl literal = new LiteralControl();
control.Parent.Controls.Add(literal);
try
{
literal.Text = (string)control.GetType().GetProperty("SelectedItem").GetValue(control, null);
}
catch
{
}
control.Parent.Controls.Remove(control);
}
else if (control.GetType().GetProperty("Text") != null)
{
LiteralControl literal = new LiteralControl();
control.Parent.Controls.Add(literal);
literal.Text = (string) control.GetType().GetProperty("Text").GetValue(control, null);
control.Parent.Controls.Remove(control);
}
}
}
更新1 我已经通过将数据放入会话然后从会话中创建excel来测试它。它也导致了同样的错误。
var dv = (DataView) Session["ScheduledOrdersReport"];
Response.Clear();
var userName = CommonMethods.GetUserId();
var fileName = string.Format("ScheduledOrdersReport-{0}-{1:yyyyMMddhhmmsstt}.xls", userName, DateTime.Now);
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel"; //"application/vnd.xls";
var stringWrite = new StringWriter();
var htmlWrite = new HtmlTextWriter(stringWrite);
var g = new GridView();
g.DataSource = dv;
g.DataBind();
g.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
更新2 我只是通过打开一个弹出窗口然后使用更新1代码进行了另一个测试。没有问题,点击或保持页面一段时间,然后再次单击该按钮。
看起来它是回复和回复明确和结束问题。
我只是暂时无法找到任何可以正确解决问题的方法。可能是我需要休息一下。
答案 0 :(得分:0)
如何启动webclient? 并设置NetworkCredentials?那么你每次都必须登录......
像:
.jqmWindow {
display: none;
position: fixed;
top: 17%;
left: 50%;
margin-left: -300px;
width: 600px;
background-color: #FFF;
color: #333;
border: 4px solid #8d8d8b;
padding: 12px;
}
`