【发布时间】:2016-08-30 02:20:58
【问题描述】:
我的 csv 数据如下所示:
Device data for period 30/08/2016 to 30/08/2016
Site ID,Time,INC1_MD
VSI-18,2016-08-30 00:00:00,165.954
VSI-18,2016-08-30 00:01:00,14.524
VSI-18,2016-08-30 00:02:00,32.920
VSI-18,2016-08-30 00:03:00,48.508
VSI-18,2016-08-30 00:04:00,62.418
.....
我尝试忽略前两行并从“VSI-18...”开始 并提取日期和时间列之后的第三列数据 并将它们导出到新的 csv 文件中,每天 1 列 喜欢:
day1,day2,day3
100,200,300
200,123,123
123,222,444
....
这是我的代码
o_csv_loc.Text = varFile; //csv data file location
save_file_loc.Text = saveloc; //new csv file location
var reader = new StreamReader(File.OpenRead(varFile));
List <string[]> listA = new List<string[]>();
List<string[]> listB = new List<string[]>();
List<string[]> listC = new List<string[]>();
//I think these two code below is to skip first 2 line of csv data
//file and start read the third line (VSI-18...)
reader.ReadLine();
reader.ReadLine();
while (reader.Peek() > -1)
{
var line = reader.ReadLine();
var values = line.Split(';');
listA.Add(new string[] { values[0] });
listB.Add(new string[] { values[1] });
listC.Add(new string[] { values[2] });
//I think that listC is suppose to extract the data after the
//second comma which is third column
}
对于导出数据代码,我还没有完成,因为我还不知道如何读取数据。 调试时,'System.IndexOutOfRangeException' 在线显示
listB.Add(new string[] { values[1] });
这条线应该没有问题吧? values[0] 还没有问题。
编辑
我成功将数据导出到新的 csv 文件
var reader = new StreamReader(File.OpenRead(varFile));
List <string[]> listA = new List<string[]>(); //here are the code
//changed
List<string[]> listB = new List<string[]>();
List<string[]> listC = new List<string[]>();
reader.ReadLine();
reader.ReadLine();
while (reader.Peek() > -1)
{
var line = reader.ReadLine();
var values = line.Split(',');
listA.Add(new string[] { values[0] });
listB.Add(new string[] { values[1] });
listC.Add(new string[] { values[2]});
}
using (System.IO.TextWriter writer = File.CreateText(saveloc))
{
for (int index = 0; index < listC.Count; index++)
{
writer.WriteLine(string.Join(",", listC[index]) + ',');
}
}
结果是这样的:
165.954,
14.524,
32.920,
48.508,
62.418,
79.151,
96.982,
我还在想如何检测新日期并放入新列
【问题讨论】:
-
你在
;上分手。我在您的文件中没有看到任何这些内容。 -
不要在 sn-p 标记中包含非 HTML/JS/CSS 代码。将其缩进四个空格就足够了(或突出显示它并单击
{}按钮)。 -
正如@Blorgbeard 提到的,我认为你想分割','而不是';'
-
当心自定义 CSV 解析器。这是一种比最初看起来更微妙的格式。
-
我很抱歉我的代码有这么小的错误,是我的错,现在读取的代码没问题,现在只需要将数据导出到新的 csv。