【发布时间】:2021-03-29 01:02:16
【问题描述】:
我在 youtube 上看过一个教程,该教程解释了如何在 excel 文件中搜索,但是当我连续搜索特定值时,我必须在搜索框中输入 column name = 'value at the row' 并且列名必须是一个单词,而不是用空格分隔的 2 个单词,否则我必须写 column name like '%value%' 以获得相似的结果。 when I search for a specific value in a row
column name must be a single word
第一:如何通过在任意行写入特定关键字进行搜索。 第二:如何在组合框中加载列名并按列名搜索并使其可选择列。 代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace excel
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btnOpen_Click(object sender, EventArgs e)
{
using(OpenFileDialog ofd = new OpenFileDialog() { Filter = "Excel Workbook|*.xlsx",Multiselect = false})
{
if (ofd.ShowDialog() == DialogResult.OK)
{
Cursor.Current = Cursors.WaitCursor;
DataTable dt = new DataTable();
using(XLWorkbook workbook = new XLWorkbook(ofd.FileName))
{
bool isFirstRow = true;
var rows = workbook.Worksheet(1).RowsUsed();
foreach(var row in rows)
{
if (isFirstRow)
{
foreach (IXLCell cell in row.Cells())
dt.Columns.Add(cell.Value.ToString());
isFirstRow = false;
}
else
{
dt.Rows.Add();
int i = 0;
foreach (IXLCell cell in row.Cells())
dt.Rows[dt.Rows.Count - 1][i++] = cell.Value.ToString();
}
}
dataGridView1.DataSource = dt.DefaultView;
lblTotal.Text = $"Total Records:{dataGridView1.RowCount}";
Cursor.Current = Cursors.Default;
}
}
}
}
private void btnSearch_Click(object sender, EventArgs e)
{
try
{
DataView dv = dataGridView1.DataSource as DataView;
if (dv != null)
dv.RowFilter = txtSearch.Text;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void txtSearch_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)13)
btnSearch.PerformClick();
}
private void label2_Click(object sender, EventArgs e)
{
}
private void txtSearch_TextChanged(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
}
}
【问题讨论】: