我有1个带有1个TextBox的表单,用户将在其中键入ProductId(FCID)
,然后按Enter键,然后,基于此,我要用搜索结果填充DataGridView。
这里有2个问题:
如何根据用户输入的FCID
从Excel过滤记录?
从Excel绑定数据源时,如何如第二幅图像所示删除空白记录?
代码:
private void txtProductId_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
string pathName = txtFilePath.Text;
string fileName = System.IO.Path.GetFileNameWithoutExtension(txtFilePath.Text);
DataTable tbContainer = new DataTable();
string strConn = string.Empty;
string sheetName = fileName;
FileInfo file = new FileInfo(pathName);
if (!file.Exists) { throw new Exception("Error, file doesn't exists!"); }
string extension = file.Extension;
switch (extension)
{
case ".xls":
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
break;
case ".xlsx":
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'";
break;
default:
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
break;
}
OleDbConnection cnnxls = new OleDbConnection(strConn);
OleDbDataAdapter oda = new OleDbDataAdapter(string.Format("select * from [{0}$]", sheetName), cnnxls);
oda.Fill(tbContainer);
grdProductList.DataSource = tbContainer;
e.Handled = true;
}
}
我以前没有在Windows窗体上工作过。
答案 0 :(得分:1)
您可以指定包含要检索的数据的单元格范围。格式:
[sheet1$[Start Cell]:[End Cell]]
根据您的情况,您可以更改查询,仅将单元格从B6
更改为ZZ
(这似乎是包含数据的范围。请根据需要对其进行调整):
切记处置创建的一次性对象,或在using
块中声明它们)
string sheetName = "Sheet1";
string query = $"SELECT * FROM [{sheetName}$B6:ZZ]"
OleDbDataAdapter oda = new OleDbDataAdapter(query, cnnxls);
//(...)
oda.Dispose();
您当然可以指定一个过滤器:
int fieldID = 204;
//
string query = $"SELECT * FROM [{sheetName}$B6:ZZ] WHERE FCID = {fieldID}"
using (OleDbConnection cnnxls = new OleDbConnection(strConn))
using (OleDbDataAdapter oda = new OleDbDataAdapter(query, cnnxls))
{
oda.Fill(tbContainer);
grdProductList.DataSource = tbContainer;
}
或范围过滤器:
string query = $"SELECT * FROM [{sheetName}$B6:ZZ] WHERE FCID BETWEEN 204 AND 300"
或使用变量值:
int minValue = 204;
int maxValue = 300;
string query = $"SELECT * FROM [{sheetName}$B6:ZZ] WHERE FCID BETWEEN {minValue} AND {maxValue}"
.xls
格式不支持通用范围:
[sheet1$B6:ZZ]
。
接受 [sheet1$B6:O65535]
:数据在B6:O*
列范围内。
更新 :(特定于此问题):
鉴于Excel工作表的组成,需要明确指定字段名称,否则生成的DataTable
将包含空列:
int fieldID = 204;
string fieldSelector = "[ FCID], [Product Name], [Category], [Sub Category], " +
"[Brand], [MRP], [Disc %], [Stock], [Discount Type]";
query = $"SELECT {fieldSelector} FROM [{sheetName}$B6:O65535] WHERE [ FCID] = {fieldID}";