如何将每条线分成不同的细胞?我用逗号分隔信息行,但我想将它们分开。
string path = @"..\Debug\data\IrisData.csv";
var content = File.ReadAllText(path);
var contentLines = content.Split('\n');
var csv = from line in contentLines
select line.Split(',').ToArray();
using (StreamWriter sw = new StreamWriter(path, true))
{
foreach (var data in csv)
{
foreach (var cell in data)
{
var newline = string.Format("{0}", cell);
newline = cell != data[4] ? newline + "," : newline;
sw.Write(newline);
}
sw.Write(Environment.NewLine);
}
}
Console.WriteLine("Press any key to continue...");
Console.ReadLine();
答案 0 :(得分:1)
您可以尝试这样:
newline = cell != data[4] ? "\"" + newline + "\"," : newline;
这可以帮到你
答案 1 :(得分:1)
";"
将数据分隔到不同的单元格。
答案 2 :(得分:0)
我不确定我是否理解你的问题。
您是否尝试将csv分开并再次组合在一起?至少那是你的代码对我来说的样子..
我不喜欢为每个变量使用var
,因为它可能导致错误或意外行为。我觉得这也发生在你身上。
String.Split(char)
返回string[]
foreach (var data in csv) // csv is a string[] -> data is a string
{
// data is a string which is basically a char[] -> cell is a char
// I don't think, that's what you wanted...
foreach (var cell in data)
{
var newline = string.Format("{0}", cell);
newline = cell != data[4] ? newline + "," : newline;
sw.Write(newline);
}
sw.Write(Environment.NewLine);
}
也许你可以告诉我,你真正想做什么,所以我可以帮助你:)
答案 3 :(得分:0)
您可以查看TextFieldParser:
确保添加对Microsoft.VisualBasic程序集的引用,并添加using Microsoft.VisualBasic.FileIO;
using (TextFieldParser parser = new TextFieldParser(@"..\Debug\data\IrisData.csv"))
{
parser.SetDelimiters(new String[] { "," });
while (!parser.EndOfData)
{
string[] fields = parser.ReadFields();
// fields will contain every seperated cell
}
}