如何从dgv中将选定的行导出到excel中?以下是我的代码,用于导入excel并查找值。如何只将选定的行从datagridview导出到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)
{
}
}
是你的问题才刚刚选定的行,或者您的问题导出到Excel? – VahidNaderi
上面的代码对于选择行很好,但我需要输出到excel的代码(只有选中)。 – Pravii