跳过csv文件中的第一行 [英] Skip first line in csv file

查看:138
本文介绍了跳过csv文件中的第一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





以下是我的CSV内容



受管系统的数量,
80,合规

7,non_colpliance



我只需要这些值(80和7)。我需要跳过剩下的数据



以下是我的代码



 StreamReader sr =  new  StreamReader(filepath); 
string line = sr.ReadLine();
string [] value = line.Split(' ,');
DataTable dt = new DataTable();
DataRow行;
foreach 字符串 dc value
{
dt.Columns.Add( new DataColumn(dc ));
}
while (!sr.EndOfStream)
{
value = sr.ReadLine()。分割(' ,');
if value .Length == dt.Columns.Count)
{
row = dt.NewRow();
row.ItemArray = value ;
dt.Rows.Add(row);
}
}





请帮我解决这个问题。



在此先感谢。

解决方案

在一开始就添加另一个 ReadLine ;它将跳过第一行。当你使用 Split 的结果时,只使用索引0处结果数组的元素。这就是全部。



更好,因为你的文件很小,而不是使用 String.Reader ,使用 System.IO.File.ReadAllLines 。它将返回行数组,因此您可以忽略索引为0的行。请参阅:

http://msdn.microsoft.com/en-us/library/system.io.file.readalllines.aspx [ ^ ]。



-SA


检查以下链接。



< a href =File.ReadAllLines Method(String)> File.ReadAllLines方法示例


为什么要读取CSV文件使用Reader [ ^ ]如果可以使用 OLEDB [ ^ ] to 导入数据 [ ^ ]

Hi,

Below is my CSV content

Number of managed system,
80, compliance
7, non_colpliance

I need only these values (80 and 7). I need to skip the rest of the data

Below is my code

StreamReader sr = new StreamReader(filepath);
            string line = sr.ReadLine();
            string[] value = line.Split(',');
            DataTable dt = new DataTable();
            DataRow row;
            foreach (string dc in value)
            {
                dt.Columns.Add(new DataColumn(dc));
            }
            while ( !sr.EndOfStream )
            {
                value = sr.ReadLine().Split(',');
                if(value.Length == dt.Columns.Count)
                {
                    row = dt.NewRow();
                    row.ItemArray = value;
                    dt.Rows.Add(row);
                }
            }



Please help me to achive this.

Thanks in advance.

解决方案

Add another ReadLine in the very beginning; it will skip first line. When you use result of Split, use only the element of the resulting array at index 0. That's all.

Better yet, as your file is small, instead of using String.Reader, use System.IO.File.ReadAllLines. It will return you the array of lines, so you can ignore the line with the index 0. Please see:
http://msdn.microsoft.com/en-us/library/system.io.file.readalllines.aspx[^].

—SA


Check following link.

File.ReadAllLines Method with example


Why to read CSV file using Reader[^] if it possible to use OLEDB[^] to import data[^]?


这篇关于跳过csv文件中的第一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆