为什么不回复于()导出CSV文件,浏览器? [英] Why won't Response.Write() export a CSV file to the browser?

查看:133
本文介绍了为什么不回复于()导出CSV文件,浏览器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一个DataTable的内容导出到用户的浏览器作为一个Excel .csv文件。当我在调试器中通过点击我的code中的导出按钮,然后一步,一切都看起来像它的发生,但没有文件实际上被发送到浏览器。关键是,我用这完全一样的code在另一个项目和它的作品出现。

I'm trying to export the contents of a DataTable to the user's browser as an Excel .csv file. When I click the "Export" button and step through my code in the debugger, everything looks like it's happening, but no file actually gets sent to the browser. The thing is, I'm using this EXACT SAME CODE in another project and it works there.

修改:这是我的ASPX标记包含按钮,整个的UpdatePanel:

EDIT: Here's my ASPX markup for the entire UpdatePanel containing the button:

<asp:UpdatePanel ID="updNoUsage" runat="server">
  <ContentTemplate>
    <asp:Button ID="btnNoUsageLookup" runat="server" Text="Get No Usage Lines Report"
      OnClick="btnNoUsageLookup_Click" /><br /><br />
    <asp:Label ID="lblNoUsageMessage" runat="server" Font-Bold="True" ForeColor="Blue"
      Text="Message" Visible="False"></asp:Label><br /><br />
    <asp:Panel ID="pnlNoUsageReport" runat="server" Visible="False" BorderStyle="None">
      <asp:GridView ID="gvNoUsage" runat="server" AllowPaging="True" AllowSorting="True"
        AutoGenerateColumns="False" BorderColor="#666666" BorderStyle="Solid"
        BorderWidth="1px" PageSize="25" OnPageIndexChanging="gv_PageIndexChanging"
        OnSorting="gv_Sorting" OnRowCreated="gvNoUsage_RowCreated">
          <HeaderStyle BackColor="Transparent" />
          <RowStyle BackColor="#e5e5e5" />
          <AlternatingRowStyle BackColor="White" />
          <Columns>
            <asp:BoundField DataField="CostCenter" HeaderText="Cost Center" SortExpression="CostCenter" />
            <asp:BoundField DataField="WirelessNumber" HeaderText="Wireless Number" SortExpression="WirelessNumber" />
            <asp:BoundField DataField="ESN" HeaderText="ESN" SortExpression="ESN" />
            <asp:BoundField DataField="UserName" HeaderText="User Name" SortExpression="UserName" />
            <asp:BoundField DataField="Model" HeaderText="Handset Model" SortExpression="Model" />
          </Columns>
        </asp:GridView>
        <ajaxToolkit:AnimationExtender ID="aeNoUsage" runat="server" 
          TargetControlID="gvNoUsage">
          <Animations>
            <OnLoad>
              <Sequence>
        <FadeIn AnimationTarget="gvNoUsage" Duration=".25" />
          </Sequence>
            </OnLoad>
          </Animations>
        </ajaxToolkit:AnimationExtender>
        <br /><br />
        <asp:Button ID="btnNoUsageExport" runat="server" CausesValidation="false" 
          Text="Export to Excel" OnClick="btnExport_Click" />
      </asp:Panel>
    </ContentTemplate>
    <Triggers>
      <asp:AsyncPostBackTrigger ControlID="btnNoUsageLookup" EventName="Click" />
      <asp:AsyncPostBackTrigger ControlID="btnNoUsageExport" EventName="Click" />
    </Triggers>
  </asp:UpdatePanel>

下面是在后面的code中的btnExport_ClickC#功能:

Here's the "btnExport_Click" C# function in the code behind:

protected void btnExport_Click(object sender, EventArgs e)
{
  //Get dataset and output filename
  DataTable dt = dtNoUsage;
  string exportFile = "No Usage Report.csv";

  //Now convert DataSet to a CSV file
  //  Clear the response so there is nothing coming back.
  Response.Clear();
  Response.ClearHeaders();

  //  Add an HTTP header for the content type to tell the browser that this is a file that is being passed back.
  Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", exportFile));

  //  Tell the browser the correct file type (should cause the file to open with Microsoft Excel)
  Response.ContentType = "application/vnd.ms-excel";

  //  Get CSV file from DataTable
  string csvData = HelperFunctions.CreateCSVFile(dt);

  //  Write the response to the HTTP stream back to the client browser
  Response.Write(csvData);

  //  End the stream write and commit it
  Response.End();
}

下面是HelperFunctions.CreateCSVFile()方法:

Here's the HelperFunctions.CreateCSVFile() method:

public static string CreateCSVFile(DataTable dt)
{
  //  Build the file line by line from the DataSet
  StringBuilder sbFile = new StringBuilder();

  //  Add the header row
  for (int i = 0; i < dt.Columns.Count; i++)
  {
    sbFile.AppendFormat("{0}", EscapeCSVField(dt.Columns[i].ColumnName));
    if (i < dt.Columns.Count - 1)
    {
      sbFile.Append(",");
    }
  }
  //  Add a newline
  sbFile.AppendLine(String.Empty);
  //  Add the data rows
  for (int i = 1; i < dt.Rows.Count; i++)
  {
    for (int j = 0; j < dt.Columns.Count; j++)
    {
      sbFile.AppendFormat("{0}", EscapeCSVField(dt.Rows[i][j].ToString().Trim()));
      if (j < dt.Columns.Count - 1)
      {
        sbFile.Append(",");
      }
    }
    //  Add a newline
    sbFile.AppendLine(String.Empty);
  }
  return sbFile.ToString();
}

就像我说的,这同code在另一个项目中正常使用。任何想法可能会发生什么?

Like I said, this same code is working perfectly in another project. Any ideas what might be happening?

修改:我看到在提琴手的反应,并尽可能我可以告诉大家,正确的反应是回来 - 浏览器(Chrome浏览器,IE,火狐),只是没有响应文件被发送。这里的反应是什么样子:

EDIT: I watched the response in Fiddler, and as far as I can tell, the correct response is coming back - the browsers (Chrome, IE, Firefox) are just not responding to the file that is sent. Here's what the response looks like:

HTTP/1.1 200 OK
Cache-Control: public
Content-Type: application/vnd.ms-excel; charset=utf-8
Server: Microsoft-IIS/8.0
Content-Disposition: attachment; filename=Upgrade Eligibility Report.csv
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?YzpcdXNlcnNcdGltb3RoeWJcZG9jdW1lbnRzXHZpc3VhbCBzdHVkaW8gMjAxMlxQcm9qZWN0c1xXaXJlbGVzc0JpbGxpbmdWMlxXaXJlbGVzc0JpbGxpbmdWMlxVc2VyXFdpcmVsZXNzQmlsbGluZy5hc3B4?=
X-Powered-By: ASP.NET
Date: Tue, 29 Oct 2013 15:19:43 GMT
Content-Length: 16310

然后有一个空行,文件内容被导出。内容也看起来是正确的。我感到困惑。

Then there's a blank line and the file contents are dumped. The contents also look correct. I'm baffled.

推荐答案

在UpdatePanel可能是这里的问题。你直接写文件的反应,但在UpdatePanel使用微软的AJAX时髦的巫毒教,它预计其结果回来为HTML和数据的自己的特殊品种。我敢打赌他们的JavaScript抛出一个错误。

The UpdatePanel is probably the problem here. You're writing the file directly to the response, but the UpdatePanel is using Microsoft's funky AJAX voodoo, which expects its result to come back as its own special breed of HTML and data. I'd bet their javascript is throwing an error.

如果您从更新面板删除的按钮,你应该确定。

If you remove the button from the update panel, you should be ok.

这篇关于为什么不回复于()导出CSV文件,浏览器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆