如何将选定的行从 dgv 导出到 excel 中?下面是我用于导入 excel 并查找值的代码。
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
//this.textBox1.Text = openFileDialog1.FileName;
//string PathConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + textBox1.Text + ";Extended Properties=\"Excel 8.0;HDR=Yes:\";";
String PathConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + openFileDialog1.FileName + ";Extended Properties=\"Excel 12.0 XML;HDR=Yes:\";";
OleDbConnection conn = new OleDbConnection(PathConn);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("Select * from [sheet1$]", conn);
DataTable dt = new DataTable();
myDataAdapter.Fill(dt);
dataGridView1.DataSource = dt;
}
}
private void button2_Click(object sender, EventArgs e)
{
dataGridView1.ClearSelection();
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
try
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells["Name"].Value.ToString().ToUpperInvariant().Contains(textBox1.Text.ToUpperInvariant()))
{
dataGridView1.Rows[row.Index].Selected = true;
}
}
}
catch (Exception)
{
}
}