根据列值从Excel电子表格中选择行并将其插入到DataGridView中,可以通过使用开源库NPOI来实现。下面是一个示例代码,展示了如何从Excel文件中读取数据,并根据特定列的值选择行并插入到DataGridView中:
using System;
using System.Data;
using System.Windows.Forms;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
public class ExcelReader
{
public static DataTable ReadExcel(string filePath, string sheetName)
{
DataTable dt = new DataTable();
using (var fs = File.Open(filePath, FileMode.Open, FileAccess.Read))
{
var workbook = new XSSFWorkbook(fs);
var sheet = workbook.GetSheet(sheetName);
// 获取列标题
var headerRow = sheet.GetRow(0);
foreach (var cell in headerRow.Cells)
{
dt.Columns.Add(cell.ToString());
}
// 读取数据行
for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
{
var row = sheet.GetRow(i);
var newRow = dt.NewRow();
// 检查特定列的值并选择行
if (row.GetCell(0).ToString() == "某个特定列的值")
{
for (int j = row.FirstCellNum; j < row.LastCellNum; j++)
{
newRow[j] = row.GetCell(j).ToString();
}
dt.Rows.Add(newRow);
}
}
}
return dt;
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "Excel文件|*.xlsx;*.xls";
openFileDialog1.Title = "选择Excel文件";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string filePath = openFileDialog1.FileName;
string sheetName = "Sheet1"; // 根据实际情况设置sheet名称
DataTable dt = ExcelReader.ReadExcel(filePath, sheetName);
dataGridView1.DataSource = dt;
}
}
}
上述代码中,使用了NPOI来读取Excel文件并将数据存储到DataTable中,然后将DataTable绑定到DataGridView控件上。你需要根据实际情况修改代码中的文件路径、sheet名称以及特定列的值。
推荐的腾讯云相关产品:腾讯云对象存储(COS),详情请参考腾讯云COS官方文档:https://cloud.tencent.com/product/cos。
领取专属 10元无门槛券
手把手带您无忧上云