Excel到Datagridview过滤器和位置

问题描述 投票:0回答:1

我已将Excel电子表格导入到C#中的Windows窗体应用程序的datagridview中。然而,我需要通过2个条件过滤数据,这些条件是2个单独的文本框等于用户输入的特定值。我附上了我的表格的代码和截图。我需要过滤器进入“btnFetch”点击事件:i.stack.imgur.com/GA6SX.png

我需要通过数据中的那些代码过滤数据,例如,出发机场= BIKF和到达机场=到EGGW,它只会带来那些行。

还有一种方法可以让用户选择要通过弹出窗口导入的Excel文件的位置吗?码:

public class frmMain : Form{
    public frmMain()
    {
        InitializeComponent();
    }

    private void frmMain_Load(object sender, EventArgs e)
    {
        dg1.Visible = true;
        pb1.ImageLocation = “C:/…abc.png;
        pb1.SizeMode = PictureBoxSizeMode.Zoom;
    }
    private void btnOpen_Click(object sender, EventArgs e)
    {
        OleDbConnection conn = new OleDbConnection();
        conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source = C:….abc.xlsx” + @";Extended Properties=""Excel 8.0; HDR=Yes; IMEX=1; ImportMixedTypes=Text;TypeGuessRows=0""";

        OleDbCommand command = new OleDbCommand("SELECT * FROM [Sheet1$]",conn);

        DataSet ds = new DataSet();
        OleDbDataAdapter adpt = new OleDbDataAdapter(command);
        adpt.Fill(ds);

        dg1.DataSource = ds.Tables[0];
    }
    private void btnFetch_Click(object sender, EventArgs e)
    {

    }

    private void btnClear_Click(object sender, EventArgs e)
    {
        txtDepAir.Text = "";`enter code here`
        txtDestAir.Text = "";
    }
}
c# excel forms winforms datagridview
1个回答
1
投票

有没有办法让用户选择excel文件?

是的,有一种方法,只需使用OpenFileDialog

using (OpenFileDialog OFPD = new OpenFileDialog)
{
if (OPD.ShowDialog== DialogResult.OK) {
    OleDbConnection con = new OleDbConnection("DataSource =" + OPD.FileName + "......");
  {

   }}}

提示:如果检索到单个表,则数据集无用。

通过2个条件过滤数据,这些条件是2个单独的文本框

你也可以这样做。如上所述,要么你只使用DataTable,要么使用DataReader

使用DataTable进行过滤

using (SqlCommand command = new SqlCommand("SELECT * FROM [Sheet1$] WHERE [ONE COLUMN NAME]=@col1 AND [2nd COLUMN NAME]=@col2",conn)
 {
 command.Parameters.Add("@col1",OledbType.VarChar).Value = txtbx1.Text;
 command.Parameters.Add("@col2",OledbType.VarChar).Value = txtbx2.Text;
 DataTable dt = new DataTable;
 SqlDataAdapter ada = new SqlDataAdapter(command);
 ada.Fill(dt)
 DataGrdView1.DataSource = dt;
 }}

使用dataReader过滤

 using (SqlCommand command = new SqlCommand("SELECT * FROM [Sheet1$] WHERE [ONE COLUMN NAME]=@col1 AND [2nd COLUMN NAME]=@col2",conn)
 {
 command.Parameters.Add("@col1",OledbType.VarChar).Value = txtbx1.Text;
 command.Parameters.Add("@col2",OledbType.VarChar).Value = txtbx2.Text;
 SqlDataReader dr = command.ExecuteReader;
 DataGridView1.Rows.Clear();
 while (dr.read)
 {
  DataGridViewRow row =  (DataGridViewRow)yourDataGridView.Rows[0].Clone();
  row.Cells[0].Value = "XYZ";
  row.Cells[1].Value = 50.2;
  DataGridView1.Rows.Add(row);
  }}}

希望这可以帮助你:)

© www.soinside.com 2019 - 2024. All rights reserved.