我正在使用Xamarin.Forms创建数据收集应用程序。该应用程序的一个特殊功能是通过csv导出数据。捕获后,将使用以下方法将数据写入文本文件:
public void WriteToFile(string CompanyName, string Website, string FirsttName, string LastName, string JobTitle, string Phone, string Email, string Solution, string Notes, string ContactOwner, string EventName)
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string filename = System.IO.Path.Combine(path, "Prospects.txt");
string lineToBeAdded = string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10}", CompanyName, Website, FirsttName, LastName, JobTitle, Phone, Email, Solution, Notes, ContactOwner, EventName);
File.AppendAllText(filename, lineToBeAdded + Environment.NewLine);
}
我的问题是,在NOTES变量中,用户在描述中使用逗号,弄乱了csv的结构。
如何强制忽略此字符串中的逗号?
答案 0 :(得分:3)
要避免逗号使每列用双引号引起来,请使用2个双qoutes代替双qoutes来代替双qoutes:
string lineToBeAdded = string.Format("\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\",\"{8}\",\"{9}\",\"{10}\"",
CompanyName.Replace("\"","\"\""),
Website.Replace("\"","\"\""),
FirsttName.Replace("\"","\"\""),
LastName.Replace("\"","\"\""),
JobTitle.Replace("\"","\"\""),
Phone.Replace("\"","\"\""),
Email.Replace("\"","\"\""),
Solution.Replace("\"","\"\""),
Notes.Replace("\"","\"\""),
ContactOwner.Replace("\"","\"\""),
EventName.Replace("\"","\"\""));
答案 1 :(得分:1)
创建此功能:
string GetCsvLine(params string[] fields) =>
string.Join(",", fields.Select(x => $"\"{x.Replace("\"", "\"\"")}\""));
这样调用它,替换示例代码中初始化“ lineToBeAdded”的行:
string lineToBeAdded = GetCsvLine(CompanyName, Website, FirsttName, LastName, JobTitle, Phone, Email, Solution, Notes, ContactOwner, EventName);
请参考here - RFC4180-CSV规范:
总结:
答案 2 :(得分:0)
此外,您不必使用逗号,也可以使用|。或其他用户不使用的内容。
要使其更加友好,您可以在第一行中指定定界符,Excel支持这一点。
sep=|
header1|header2|header3
1,2|2,3|3,4