Opening text containing CSV with Excel from ASP.NE

2019-08-20 10:27发布

I'm converting an older asp.net intranet application over to .net 4.5. One of the parts I'm having trouble with is supposed to open a string containing CSV data into Excel.

No matter how I attempt to accomplish this, the resulting excel document contains the contents of the website rather than the text I supplied.

On an additional note, I currently have the aspx in a web project, while the utility/business classes reside in another. I don't know if that is part of the problem.

Please help me out with this issue.

CSV sample:

string text = "\"Year\", \"Make\", \"Model\", \"Length\"\n\"1997\", \"Ford\", \"E350\", \"2.34\"\n\"2000\", \"Mercury\", \"Cougar\", \"2.38\""

Code Sample:

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();
}

Update: The resulting file contains the website contents rather than the CSV text.

<!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

1条回答
2楼-- · 2019-08-20 10:53

The answer is to reboot your PC. Yes, it's working now without any further code changes. I just can't believe I spent so long trying to get this to work properly.

Thank you for trying to help, Tim.

查看更多
登录 后发表回答