c# - c#如何按预期名称在excel文件中搜索,没有'%example'%或列名='行值'之类的类型
问题描述
我在 youtube 上观看了一个教程,该教程解释了如何在 excel 文件中进行搜索,但是当我在一行中搜索特定值时,我必须在搜索框中输入列名 = '行中的值',并且列名必须是一个单词,而不是用空格分隔的 2 个单词,否则我必须写出像 '%value%' 这样的列名才能获得类似的结果。 当我连续搜索特定值时
第一:我如何通过在任何行写一个特定的关键字来搜索。 第二:如何在组合框中加载列名并按列名搜索并使选择列成为可选。 代码:
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)
{
}
}
}
解决方案
static string ColumnNumberToColumnLetter(int colIndex)
{
int colnum = colIndex;
string columnLetter = null;
int mod = 0;
while (colnum > 0)
{
mod = (colnum - 1) % 26;
columnLetter = (char)(65 + mod) + columnLetter;
colnum = (int)((colnum - mod) / 26);
}
return columnLetter;
}
string columnLetter = ColumnNumberToColumnLetter(27); //return AA
推荐阅读
- javascript - Discord Bot 自动批量删除问题
- .htaccess - .htaccess(强制 https 和无 www)不起作用
- java - 有人能告诉我写这行代码的不同方式吗?
- amp-html - 如何在单击它的同一框架中打开 amp login(不是弹出窗口)?
- javascript - 我的 .js 文件不会链接到我的 HTML,无法让 scrollmagic 工作
- javascript - 如何使多个图像在使用 jQuery 单击时消失?
- c# - 搜索名称包含特定数字的文件
- html - 如果用户设备没有互联网连接,我希望我的网站显示某个页面,通知他们他们处于离线状态
- csv - 将 CSV 文件作为矩阵导入
- python - 使用边列表时如何检查循环?