我用代码打开一个.csv文件,我希望选择一个定界符并定义列(标题名称)。我需要知道如何定义它们。我使用以下方式生成文件:
fnresultfile = new StreamWriter("Resultfile_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".csv", true); //Filename
fnresultfile.WriteLine("Data recorded on date : " + DateTime.Now);
fnresultfile.WriteLine("The parameters of this Test Sequence were set to :");
fnresultfile.WriteLine("X =" + Xactual + ",Y =" + Yactual + ",Z =" + Zactual);
fnresultfile.WriteLine("Key Orientation = " + Key_OrientationBox.Text);
fnresultfile.Close();
答案 0 :(得分:0)
CSV文件只是一个文本文件。 按照约定/协议,它会将数据保存在带有记录的行中,并以逗号(“,”或“;”)分隔。有或没有标题(标题)。
因此,您可以像添加示例中的数据一样添加列标题。 和分隔符一样,您也可以将其添加为变量,就像添加数据一样。
不确定您的示例是否正在编写列标题。 如果是这样,下面有一个示例。例如,您可以更改字符串数组以首先使用StringBuilder建立数据。
using System;
using System.IO;
// Based on an example from Microsoft: https://docs.microsoft.com/en-us/dotnet/standard/io/how-to-write-text-to-a-file
class Program
{
static void Main(string[] args)
{
string delimitor = ",";
// Create a string array with the lines of text
string[] lines =
{
$"data record 1,data record 2,data record 3,data record 4", // First data line
$"data record 1,data record 2,data record 3,data record 4", // Second data line
$"data record 1,data record 2,data record 3,data record 4" // Third data line
};
var filename = "Resultfile_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".csv"
// Set a variable to the Documents path.
string docPath =
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
// Write the string array to a new file named "WriteLines.txt".
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, filename)))
{
foreach (string line in lines)
outputFile.WriteLine(line);
}
}
}
结果将是:
Data recorded on date,The parameters of this Test Sequence were set to,X,Key Orientation
data record 1,data record 2,data record 3,data record 4
data record 1,data record 2,data record 3,data record 4
data record 1,data record 2,data record 3,data record 4
答案 1 :(得分:-2)
使用string.Join()方法:
string[] line = {
"Data recorded on date : " + DateTime.Now,
"The parameters of this Test Sequence were set to :",
"X =" + Xactual + ",Y =" + Yactual + ",Z =" + Zactual,
"Key Orientation = " + Key_OrientationBox.Text,
};
string separator = ",";
fnresultfile.WriteLine(string.Join(separator,line));
fnresultfile.Close();