c# - 如何根据列值从 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);
}
但我不确定如何编码
解决方案
我不确定你上面的代码是什么工作,但如果你的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
}
}
}
推荐阅读
- sql - 如何存储一个值以便以后在 SQL 中使用它?
- h.264 - 在分析h264时,Elecard Stream Eye中的比特分配点和大小是什么意思?
- javascript - 给定一个 div 如何选择一个 div 中的所有 contenteditable 插入符号
- python - 为什么我的备忘录对象打印 Python 中数组的所有组合?
- intellij-idea - WebStorm 打开几个空窗口
- python-3.x - 优化 python 练习。示例:k == 1 或 k == 2 或 k == 3
- python-3.x - 一次从多列中查找混合数据类型
- windows - 用于格式化源日期的 Windows bat 文件脚本
- javascript - 刀片模板 laravel 中的 javaScript 我有一个可在我的 php 网站上使用的图像滑块。但是,当我将确切的代码放在刀片上时不起作用
- database - Oracle Instant Client 时区文件位于何处?