【发布时间】:2013-07-04 00:25:06
【问题描述】:
如何将选定的行从 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)
{
}
}
【问题讨论】:
-
您的问题是仅获取选定的行,还是导出到 excel 时遇到问题?
-
上面的代码可以很好地选择行,但我需要导出到excel的代码(只选择)。