将CSV的一部分导入datagridview

时间:2017-06-26 08:21:52

标签: c# .net csv datagridview

我所拥有的是已导入Datagridview的CSV。

我现在正在寻找一种方法来只导入带有标题#和延迟的列,而不是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;
    }
}

2 个答案:

答案 0 :(得分:1)

当我从CSV文件中读取数据时,我会为每一行创建一个值列表,并使用该列表作为我对数据库的INSERT语句的基础。

我知道在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.
        }
    }
}

以同样的方式,您可以构建列表/数据集/无论作为数据网格视图的数据源。我会建一张桌子。

这是一个模型(我现在还没有时间对它进行测试,但它应该让你走上正轨)。

DataTable table = new DataTable();
table.Columns.Add("#");
table.Columns.Add("Delay");

foreach (var line in raw_text)
{
    DataRow row = table.NewRow();
    row[0] = line[0]; // The # value you want.
    row[1] = line[1]; // The Delay value you want.

    table.Rows.Add(row);
}

DataGridView1.DataSource = table;
DataGridView1.DataBind();

答案 1 :(得分:0)

使用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;