简体   繁体   English

在C#中将CSV用作datagridview的数据源

[英]Using a CSV as a datasource for a datagridview in c#

I have a CSV file that I want to be my data source for a datagridview, but before the column headers there are 3 random lines, which are not needed and affect the table 我有一个CSV文件,我想作为datagridview的数据源,但是在列标题之前有3条随机行,它们是不需要的并且会影响表

For example: 例如:

Username: 01   
Date: 04/02/13   
*blank*            
Source, file, date, time

The code I am using to get the CSV and use it as the datagridview: 我用来获取CSV并将其用作datagridview的代码:

{
   string conStr = @"Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" + Path.GetDirectoryName(Path.GetFullPath(path)) + ";Extensions=csv,txt";
   OdbcConnection conn = new OdbcConnection(conStr);

   OdbcDataAdapter da = new OdbcDataAdapter("Select * from [" + Path.GetFileName(path) + "]", conn);
   DataTable dt = new DataTable(path);
   da.Fill(dt);

   dataGridView1.DataSource = dt;

   da.Dispose();
   conn.Close();
   conn.Dispose();
}

So basically, I need to read all the CSV for the table, but delete the first 3 lines of the text. 因此,基本上,我需要读取表的所有CSV,但要删除文本的前3行。 Is there a way to do this as a query? 有没有办法做到这一点作为查询?

You could use .NET txtReader for Text files 您可以将.NET txtReader用于文本文件

It supports the following connectionstring options that might come in handy for you 它支持以下可能适合您的connectionstring选项

  • Skip Rows 跳过行
  • Has Header 有标题
  • Ignore Empty Lines 忽略空行

Here is an example connection string: 这是一个示例连接字符串:

 Data Source='C:\MyFolder';Delimiter=',';Has Quotes=True;Skip Rows=0;Has Header=True;
 Comment Prefix='';Column Type=String,String,String,Int32,Boolean,String,String;
 Trim Spaces=False;Ignore Empty Lines=True;

Insert the following lines after you fill the datatable and before you assign it to your gridview's datasource: 在填充数据表之后,然后将其分配给gridview的数据源之前,请插入以下行:

 dt.Rows[0].Delete();
 dt.Rows[1].Delete();
 dt.Rows[2].Delete();
 dt.AcceptChanges();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM