CSV数据以线性方式格式化

时间:2016-07-13 08:28:37

标签: c# csv

我有一个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

2 个答案:

答案 0 :(得分:2)

如果你不想在每个循环中创建一个新行,只需使用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());

答案 1 :(得分:1)

尝试Write(string value)方法而不是WriteLine(string value)例如。 sw.Write(Data + "|");

using (StreamWriter sw = new StreamWriter(pathname + "MeterLogDataON_" + System.DateTime.Now.ToString("dd-MM-yyyy") + ".csv", true))
{
            sw.Write(Data + "|");
}