首页 > 解决方案 > 如何根据列值从 Excel 电子表格中选择行并将其插入 dataGridViews?

问题描述

我正在创建一个 Winform,它有一个带有三个选项卡的选项卡控件,每个选项卡都包含自己的 dataGridViews。我有一个 excel 电子表格,其中包含所有三个表的数据。这些都具有相同的标题(名称、类型、日期、成本)。共有三种不同的类别type,即雇用、搬迁和服务。我想创建一个方法,该方法基于某种 where 子句将文件中的数据插入到三个 dataGridViews,该子句根据它们的类型将它们分开。

这是我到目前为止所拥有的。我添加了一些评论来帮助解决我的问题:

    if (System.IO.File.Exists(@"C:\temp\Activity.csv"))
    {
        string[] lines = File.ReadAllLines(path + file);
        string[] data;

        for (int i = 0; i < lines.Length; i++)
        {
            data = lines[i].ToString().Split(',');

            string[] row = new string[data.Length];

            for (int j = 0; j < data.Length; j++)
            {
                row[j] = data[j].Trim();
            }
            
            //dgv1 is the dataGridView for hire
            form.dgv1.Rows.Add(row); //I want to add the excel row to this datagrid if the 'type' column = hire

            //dgv2 is the dataGridView for service
            form.dgv2.Rows.Add(row);//I want to add the excel row to this datagrid if the 'type' column = service

            //dgv3 is the dataGridView for relocate
            form.dgv3.Rows.Add(row);//I want to add the excel row to this datagrid if the 'type' column = relocate
        }
    }

以下是文件外观的示例: | 姓名 | 类型 | 日期 | 成本 | | ----- | -------- | ---------- | ---- | | 杰克 | 服务 | 2021 年 3 月 18 日 | 499 | | 约翰 | 租用 | 23/02/2021 | 199 | | 史蒂夫 | 租用 | 2020 年 1 月 11 日 | 249 | | 苏西 | 搬迁 | 21/03/2021 | 44 |

它会做这样的事情:

            if (Type = hire)
            {
                dgv1.Rows.Add(row);
            }
            if (Type = service) {
                dgv2.Rows.Add(row);
            }

            if (Type = relocate)
            {
                dgv3.Rows.Add(row);
            }

但我不确定如何编码

标签: c#excelwinformsdatagridview

解决方案


我不确定你上面的代码是什么工作,但如果你的row变量从你的列中填充了正确的值,那么你应该能够检查row数组中第二项的值来获取类型。数组中的第二项row应与类型相对应。

所以你应该能够做这样的事情:

if (System.IO.File.Exists(@"C:\temp\Activity.csv"))
{
    string[] lines = File.ReadAllLines(path + file);
    string[] data;

    for (int i = 0; i < lines.Length; i++)
    {
        data = lines[i].ToString().Split(',');

        string[] row = new string[data.Length];

        for (int j = 0; j < data.Length; j++)
        {
            row[j] = data[j].Trim();
        }

        //dgv1 is the dataGridView for hire
        if (row[1] == "hire")
        {
            form.dgv1.Rows.Add(row); //I want to add the excel row to this datagrid if the 'type' column = hire
        }
        //dgv2 is the dataGridView for service
        else if (row[1] == "service")
        {
            form.dgv2.Rows.Add(row);//I want to add the excel row to this datagrid if the 'type' column = service
        }
        //dgv3 is the dataGridView for relocate
        else if (row[1] == "relocate")
        {
            form.dgv3.Rows.Add(row);//I want to add the excel row to this datagrid if the 'type' column = relocate
        }
    }
}

推荐阅读