从ASP.NET使用Excel打开包含CSV的文本

从ASP.NET使用Excel打开包含CSV的文本,asp.net,excel,c#-4.0,csv,Asp.net,Excel,C# 4.0,Csv,我正在将旧的asp.net intranet应用程序转换为.net 4.5。我遇到问题的一个部分应该是在Excel中打开一个包含CSV数据的字符串 无论我如何尝试实现这一点,生成的excel文档都包含网站的内容,而不是我提供的文本 另外,我目前在一个web项目中拥有aspx,而实用程序/业务类则位于另一个项目中。我不知道这是否是问题的一部分 请帮我解决这个问题 CSV示例: string text = "\"Year\", \"Make\", \"Model\", \"Length\"\n\"1

我正在将旧的asp.net intranet应用程序转换为.net 4.5。我遇到问题的一个部分应该是在Excel中打开一个包含CSV数据的字符串

无论我如何尝试实现这一点,生成的excel文档都包含网站的内容,而不是我提供的文本

另外,我目前在一个web项目中拥有aspx,而实用程序/业务类则位于另一个项目中。我不知道这是否是问题的一部分

请帮我解决这个问题

CSV示例:

string text = "\"Year\", \"Make\", \"Model\", \"Length\"\n\"1997\", \"Ford\", \"E350\", \"2.34\"\n\"2000\", \"Mercury\", \"Cougar\", \"2.38\""
private static void OpenCsvFile(string text, string name)
{
    var httpContext = HttpContext.Current;
    httpContext.Response.Clear();
    httpContext.Response.ContentType = "application/vnd.ms-excel";
    httpContext.Response.Charset = "";
    httpContext.Response.AppendHeader("Content-Disposition", "attachment; filename=" + name + ".csv");
    httpContext.Response.Write(text);
    httpContext.Response.Flush();
    httpContext.ApplicationInstance.CompleteRequest();
}
代码示例:

string text = "\"Year\", \"Make\", \"Model\", \"Length\"\n\"1997\", \"Ford\", \"E350\", \"2.34\"\n\"2000\", \"Mercury\", \"Cougar\", \"2.38\""
private static void OpenCsvFile(string text, string name)
{
    var httpContext = HttpContext.Current;
    httpContext.Response.Clear();
    httpContext.Response.ContentType = "application/vnd.ms-excel";
    httpContext.Response.Charset = "";
    httpContext.Response.AppendHeader("Content-Disposition", "attachment; filename=" + name + ".csv");
    httpContext.Response.Write(text);
    httpContext.Response.Flush();
    httpContext.ApplicationInstance.CompleteRequest();
}
更新:生成的文件包含网站内容,而不是CSV文本

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head id="Head1">
    <title>
      "My WebSite"
    </title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <link href="css/style.css" type="text/css" title="WebSite" rel="stylesheet" />
  </head>
  <body>
    <form method="post" action="Main.aspx" id="form1" name="form1">
      <table border="0" cellspacing="0" cellpadding="0" id="container">
        <td class="logo" onclick="window.location='Main.aspx';">
          <div class="logoDisplay">
            <img src="images/logo.gif" alt="" width="280px" height="67px" />
          </div>
        </td>
... etc

“我的网站”
... 等

答案是重新启动电脑。 是的,它现在正在工作,没有任何进一步的代码更改。我简直不敢相信我花了这么长时间才让它正常工作


感谢您的帮助,Tim。

Try
httpContext.Response.End()HttpContext.Current.ApplicationInstance.CompleteRequest()
似乎是正确的方法。这是可行的,但网站的内容仍显示在Excel中。我希望有实际的csv文本。文本的内容是什么?什么是网站的内容?老实说,我其实不明白这个问题。