MemoryStream、StreamWriter
public ActionResult ExportCSV() { try { string Transactions = Request.Form["item"]; List<long> arr = new List<long>(); string[] strtemp = Transactions.Split(','); foreach (string strs in strtemp) { arr.Add(long.Parse(strs)); } List<PaymentMaster> PaymentList = Cerebus.GetTransactionDetails(Convert.ToInt64(this.CurrentAccount.csFacilityID), arr.ToArray()); MemoryStream stream = new MemoryStream(); StreamWriter writer = new StreamWriter(stream); writer.WriteLine("AccountName,Date,TransactionID,ItemDesc,Amount,TransactionTotal"); writer.Flush(); for (int i = 0; i < PaymentList.Count; i++) { string Summary = string.Empty; string PaymentIDF = string.Empty; string PaymentID = string.Empty; if (PaymentList[i].PaymentItems.Count > 0) Summary = DelQuota(PaymentList[i].PaymentItems[0].Summary); if (PaymentList[i].PaymentID > 0) PaymentIDF = PaymentList[i].PaymentID.ToString(); writer.WriteLine(string.Format("{0},{1},{2},{3},{4},{5}", PaymentList[i].AccountName, Convert.ToDateTime(PaymentList[i].CreateDate,Constant.GetMDDYYFormat()).ToShortDateString(), PaymentList[i].PaymentID, Summary, "$" + PaymentList[i].PaymentItems[0].Amount.ToString(), "" )); if (PaymentList[i].PaymentItems.Count > 0) { for (int j = 0; j < PaymentList[i].PaymentItems.Count; j++) { if (PaymentList[i].PaymentItems[j].PaymentID > 0) PaymentID = PaymentList[i].PaymentItems[j].PaymentID.ToString(); if (j != 0) { writer.WriteLine(string.Format("{0},{1},{2},{3},{4},{5}", "", "", PaymentID, DelQuota(PaymentList[i].PaymentItems[j].Summary), "$" + PaymentList[i].PaymentItems[j].Amount.ToString(), "" )); } } writer.WriteLine(string.Format("{0},{1},{2},{3},{4},{5}", "", "", "", "", "", "$" + PaymentList[i].Amount.ToString() )); } writer.Flush(); } stream.Position = 0; byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); stream.Close(); return File(buffer, "text/plain", "PaymentInvoice.csv"); } catch (Exception) { return View(); } }