2012-11-20 45 views
0

我正在將舊的asp.net intranet應用程序轉換爲.net 4.5。我遇到麻煩的一個部分應該是將包含CSV數據的字符串打開到Excel中。使用Excel從Excel打開包含CSV的CSV文本

無論我如何實現這一目標,生成的excel文檔都包含網站的內容,而不是我提供的文本。

在附加說明中,我目前在web項目中有aspx,而實用程序/業務類位於另一個Web項目中。我不知道這是否是問題的一部分。

請幫我解決這個問題。

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

更新:生成的文件包含網站的內容,而不是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 
+0

嘗試'httpContext.Response.End();'在最後。 –

+0

使用httpContext.Response.End();會導致錯誤:「無法評估表達式,因爲代碼已優化或本機框架位於調用堆棧之上。」 – Rethic

+2

'HttpContext.Current.ApplicationInstance.CompleteRequest()'似乎是正確的方法。 http://www.codeproject.com/Questions/231432/Howto-resolve-the-error-in-response-end –

回答

0

答案是重新啓動您的電腦。 是的,它現在工作,沒有任何進一步的代碼更改。我簡直不敢相信我花了這麼長時間努力讓這個工作正常。蒂姆,謝謝你的幫助。