我有一个for循环,在每个循环中我得到5个值。
我将CSV文件放入了文件,但数据排列不正确。
for (int i = 0, offset = 5; i < num_meters; i++, offset += 25)
{
float f_voltage, f_current, f_kw, f_kwh, f_freq, f_pf;
f_voltage = (float)Math.Round(System.BitConverter.ToSingle(my_app_msg.msg_data, (offset + 1)), 2); // voltage
f_current = (float)Math.Round(System.BitConverter.ToSingle(my_app_msg.msg_data, (offset + 5)), 5); // current
f_freq = (float)Math.Round(System.BitConverter.ToSingle(my_app_msg.msg_data, (offset + 9)), 5); // freq
f_pf = (float)Math.Round(System.BitConverter.ToSingle(my_app_msg.msg_data, (offset + 13)), 5); // pf
f_kw = (float)Math.Round(System.BitConverter.ToSingle(my_app_msg.msg_data, (offset + 17)), 2); // kw
f_kwh = (float)Math.Round(System.BitConverter.ToSingle(my_app_msg.msg_data, (offset + 21)), 2); // kwhr
//Store in CSV
vol2 = f_voltage.ToString();
Curr2 = f_current.ToString();
Feq2 = f_freq.ToString();
PF2 = f_pf.ToString();
power2 = f_kw.ToString();
energy2 = f_kwh.ToString();
DateTime time = DateTime.Now;
string Data = (time.ToString("u") + "," + power + "," + energy + "," + vol + "," + Curr + "," + Feq + "," + PF + "," + space + ",");
//Putting in CSV
using (StreamWriter sw = new StreamWriter(pathname + "MeterLogDataON_" + System.DateTime.Now.ToString("dd-MM-yyyy") + ".csv", true))
{
sw.WriteLine(Data + "\t");
}
}
但是我想要的CSV值是这样的。
VAlue1 VAlue1 VAlue1 VAlue1 VAlue1 | VAlue2 VAlue2 VAlue2 VAlue2 VAlue2 | VAlue3...so on.
但是我面临问题,因为我的数据是以这种方式存储的
VAlue1 VAlue1 VAlue1 VAlue1 VAlue1
VAlue2 VAlue2 VAlue2 VAlue2 VAlue2
最佳答案
如果不想在每个循环中创建新行,请使用sw.Write而不是sw.WriteLine
//Putting in CSV
using (StreamWriter sw = new StreamWriter(pathname + "MeterLogDataON_" + System.DateTime.Now.ToString("dd-MM-yyyy") + ".csv", true))
{
sw.Write(Data + "\t");
}
这将在循环结束时创建一个附加选项卡,并且您的代码在每个循环中打开和关闭流。我建议更改此代码以使用StringBuilder,在其中您可以在遍历数据并最后写入所有内容的同时添加文本
StringBuilder sb = new StringBuilder();
for (int i = 0, offset = 5; i < num_meters; i++, offset += 25)
{
....................
string Data = ......
sb.Append(Data + "\t");
}
// Remove the last tab
if(sb.Length > 0) sb.Length--;
string filename = (pathname + "MeterLogDataON_" + System.DateTime.Now.ToString("dd-MM-yyyy") + ".csv"
File.WriteAllText(filename, sb.ToString());
或者,如果您要附加以前的数据
File.AppendAllText(filename, sb.ToString());
关于c# - CSV数据以线性方式格式化,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38346410/