C# 将部分CSV导入datagridview

C# 将部分CSV导入datagridview,c#,.net,csv,datagridview,C#,.net,Csv,Datagridview,我拥有的是一个CSV,我已经导入到Datagridview中 我现在正在寻找一种方法,只导入标题为#和Delay的列,而不是CSV中的所有信息,因此在此方面的任何帮助都将不胜感激 以下是迄今为止我掌握的代码: private void button1_Click(object sender, EventArgs e) { DataTable dt = new DataTable(); DialogResult result = openFileDialog1.ShowDialog

我拥有的是一个CSV,我已经导入到Datagridview中

我现在正在寻找一种方法,只导入标题为#和Delay的列,而不是CSV中的所有信息,因此在此方面的任何帮助都将不胜感激

以下是迄今为止我掌握的代码:

private void button1_Click(object sender, EventArgs e)
{
    DataTable dt = new DataTable();
    DialogResult result = openFileDialog1.ShowDialog();

    if (result == DialogResult.OK) // Test result.
    {
        String Fname = openFileDialog1.FileName;
        //String Sname = "export";
        string[] raw_text = System.IO.File.ReadAllLines(Fname);
        string[] data_col = null;
        int x = 0;

        foreach (string text_line in raw_text)
        {
            data_col = text_line.Split(';');
            if (x == 0)
            {
                for (int i = 0; i < data_col.Count(); i++)
                {
                    dt.Columns.Add(data_col[i]);
                }
                x++;
            }
            else
            {
                dt.Rows.Add(data_col);
            }
        }

        dataGridView1.DataSource = dt;
    }
}
private void按钮1\u单击(对象发送者,事件参数e)
{
DataTable dt=新的DataTable();
DialogResult=openFileDialog1.ShowDialog();
if(result==DialogResult.OK)//测试结果。
{
字符串Fname=openFileDialog1.FileName;
//字符串Sname=“导出”;
string[]raw_text=System.IO.File.ReadAllLines(Fname);
字符串[]数据_col=null;
int x=0;
foreach(原始文本中的字符串文本行)
{
数据列=文本行。拆分(“;”);
如果(x==0)
{
对于(int i=0;i
当我从CSV文件中读取时,我会为每一行创建一个所需的值列表,并将该列表用作向数据库中插入
语句的基础

我知道在CSV文件中要在哪里找到数据,因此在构建查询参数列表时,我专门针对这些项目

请参阅下面的代码:

// Read the file content from the function parameter.
string content = System.Text.Encoding.ASCII.GetString(bytes);

// Split the content into an array where each array item is a line for
// each row of data.
// The Replace simply removes the CarriageReturn LineFeed characters from
// the source text and replaces them with a Pipe character (`|`)
// and then does the split from that character.
// This is just personal preference to do it this way
string[] data = content.Replace("\r\n", "|").Split('|');

// Loop through each row and extract the data you want.
// Note that each value is in a fixed position in the row.
foreach (string row in data)
{
    if (!String.IsNullOrEmpty(row))
    {
        string[] cols = row.Split(';');

        List<MySqlParameter> args = new List<MySqlParameter>();
        args.Add(new MySqlParameter("@sid", Session["storeid"]));
        args.Add(new MySqlParameter("@name", cols[0]));
        args.Add(new MySqlParameter("@con", cols[3]));

        try
        {
            // Insert the data to the database.
        }
        catch (Exception ex)
        {
            // Report an error.
        }
    }
}

使用TextFieldParser可以降低处理CVS输入的脆弱性:

// add this using statement for TextFieldParser - needs reference to Microsoft.VisualBasic assembly
using Microsoft.VisualBasic.FileIO;
...

// TextFieldParser implements IDisposable so you can let a using block take care of opening and closing
using (TextFieldParser parser = new TextFieldParser(Fname))
{
    // configure your parser to your needs
    parser.TextFieldType = FieldType.Delimited;
    parser.Delimiters = new string[] { ";" };
    parser.HasFieldsEnclosedInQuotes = false; // no messy code if your data comes with quotes: ...;"text value";"another";...

    // read the first line with your headers
    string[] fields = parser.ReadFields();

    // add the desired headers with the desired data type
    dt.Columns.Add(fields[2], typeof(string));
    dt.Columns.Add(fields[4], typeof(string));

    // read the rest of the lines from your file
    while (!parser.EndOfData)
    {
        // all fields from one line
        string[] line = parser.ReadFields();

        // create a new row <-- this is missing in your code
        DataRow row = dt.NewRow();

        // put data values; cast if needed - this example uses string type columns
        row[0] = line[2];
        row[1] = line[4];

        // add the newly created and filled row
        dt.Rows.Add(row);
    }
}

// asign to DGV
this.dataGridView1.DataSource = dt;
//为TextFieldParser添加此using语句-需要引用Microsoft.VisualBasic程序集
使用Microsoft.VisualBasic.FileIO;
...
//TextFieldParser实现IDisposable,因此您可以让using块负责打开和关闭
使用(TextFieldParser=newtextfieldparser(Fname))
{
//根据需要配置解析器
parser.TextFieldType=FieldType.Delimited;
parser.Delimiters=新字符串[]{“;”};
parser.HasFieldsEnclosedInQuotes=false;//如果数据带有引号,则不会出现混乱的代码:…;“文本值”;“另一个”;。。。
//阅读第一行的标题
string[]fields=parser.ReadFields();
//使用所需的数据类型添加所需的标题
添加(字段[2],类型(字符串));
添加(字段[4],类型(字符串));
//从文件中读取其余的行
而(!parser.EndOfData)
{
//一行中的所有字段
string[]line=parser.ReadFields();

//创建一个新行,只需通过选择所需列的索引(或只需硬编码列名并跳过第一行)来替换所有字段的
很抱歉,但是我对编程很感兴趣。你能给我一个你的意思的例子吗?虽然@ Ortund提供的答案可以给你一个大概的想法,但是考虑一下,它为处理CSV数据提供了很大的支持。嗨,Filburt,我看了TeXFieldPalsServer,不知道该怎么做。应用它将信息输入到数据表中。我对TextFieldParser的建议旨在以一种不太脆弱的方式处理CSV输入,而不是插入DGV中,这应该由现有答案来涵盖。您可以解释
Replace(“\r\n”,“|”)或
或省略它-由于OP没有提到任何拆分行的问题,对于一个声明的新手来说,这将是相当混乱的,而不是澄清。谢谢。我还没有让它工作,但会一直尝试,直到我工作。如果我真的卡住了,我会再次询问。费尔伯特我还有一个问题,我非常感谢你的帮助
// add this using statement for TextFieldParser - needs reference to Microsoft.VisualBasic assembly
using Microsoft.VisualBasic.FileIO;
...

// TextFieldParser implements IDisposable so you can let a using block take care of opening and closing
using (TextFieldParser parser = new TextFieldParser(Fname))
{
    // configure your parser to your needs
    parser.TextFieldType = FieldType.Delimited;
    parser.Delimiters = new string[] { ";" };
    parser.HasFieldsEnclosedInQuotes = false; // no messy code if your data comes with quotes: ...;"text value";"another";...

    // read the first line with your headers
    string[] fields = parser.ReadFields();

    // add the desired headers with the desired data type
    dt.Columns.Add(fields[2], typeof(string));
    dt.Columns.Add(fields[4], typeof(string));

    // read the rest of the lines from your file
    while (!parser.EndOfData)
    {
        // all fields from one line
        string[] line = parser.ReadFields();

        // create a new row <-- this is missing in your code
        DataRow row = dt.NewRow();

        // put data values; cast if needed - this example uses string type columns
        row[0] = line[2];
        row[1] = line[4];

        // add the newly created and filled row
        dt.Rows.Add(row);
    }
}

// asign to DGV
this.dataGridView1.DataSource = dt;