我的一個動作輸出一個csv文件。問題是如果一個字段包含逗號,那麼它將數據行分成兩個字段。我嘗試使用「\」」包括雙引號中的每一行,但是這是行不通的。可能有人指導我在正確的方向?使用包含逗號的數據寫入MVC中的csv
UPDATE
var sw = new StringWriter();
sw.WriteLine(String.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13}", "First Name","Last Name","Address1","Address2","City","State","Postal Code","Country","Dealer ID","Dealer Name","Survey Source","Amount","Email","Survey Code"));
sw.WriteLine(String.Format("\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\",\"{8}\",\"{9}\",\"{10}\",\"{11}\",\"{12}\",\"{13}\"", model.SurveyWinnerDetails.Select(p => p.FirstName).First().Replace("\"", "\"\""),
model.SurveyWinnerDetails.Select(p => p.LastName).First().Replace("\"", "\"\""),
model.SurveyWinnerDetails.Select(p => p.Address1).First().Replace("\"", "\"\""),
model.SurveyWinnerDetails.Select(p => p.Address2).First().Replace("\"", "\"\""),
model.SurveyWinnerDetails.Select(p => p.City).First().Replace("\"", "\"\""),
model.SurveyWinnerDetails.Select(p => p.State).First().Replace("\"", "\"\""),
model.SurveyWinnerDetails.Select(p => p.PostalCode).First().Replace("\"", "\"\""),
model.SurveyWinnerDetails.Select(p => p.CountryCode).First().Replace("\"", "\"\""),
model.SurveyWinnerDetails.Select(p => p.DealerID).First().Replace("\"", "\"\""),
model.SurveyWinnerDetails.Select(p => p.DealerName).First().Replace("\"", "\"\""),
model.SurveyWinnerDetails.Select(p => p.SurveySource).First().Replace("\"", "\"\""),
model.SurveyWinnerDetails.Select(p => p.Amount).First().Replace("\"", "\"\""),
model.SurveyWinnerDetails.Select(p => p.Email).First().Replace("\"", "\"\""),
model.SurveyWinnerDetails.Select(p => p.SurveyCode).First().Replace("\"", "\"\"")));
return File(new System.Text.UTF8Encoding().GetBytes(sw.ToString()), "text/csv", "SurveyWinner.csv");
當我現在運行它,我得到一個錯誤:對象引用未設置爲對象的實例
CSV處理程序如何處理此問題?這是你的要求應該回答的問題。 – jrummell
[還有另一個關於SO的問題,包括寫出CSV](http://stackoverflow.com/questions/1684667/writing-a-csv-file-in-net),當列包含逗號(和引號)時。 – 48klocs
您可能不應該修改現有的問題,試圖獲得不同問題的答案。在您的特定情況下,以下情況之一爲真:model爲null,model.SurveyWinnerDetails中的項目爲null,或者通過p.Something爲null所收集的某個屬性。 –