如何使用EPPlus将过滤的DataGridView数据保存到Excel中?

如何使用EPPlus将过滤的数据从DataGridView导入到Excel中? 我不知道从哪里开始,我还没有发现类似于我的问题。

这是我的保存button的代码:

 SaveFileDialog saveFileDialog1 = new SaveFileDialog(); using (MySqlConnection con = new MySqlConnection(connectionString)) { using (MySqlCommand cmd = new MySqlCommand("SELECT * FROM statusrouted.routed", con)) { cmd.CommandType = CommandType.Text; using (MySqlDataAdapter sda = new MySqlDataAdapter(cmd)) { using (DataTable dt = new DataTable()) { using (ExcelPackage pck = new ExcelPackage()) { sda.Fill(dt); ExcelWorksheet ws = pck.Workbook.Worksheets.Add(DateTime.Today.ToString("MMMM-yyyy")); ws.Cells["A2"].LoadFromDataTable( dt, true); saveFileDialog1.Title = "Save as Excel"; saveFileDialog1.FileName = ""; saveFileDialog1.Filter = "Excel files(2007)|*.xlsx"; if (saveFileDialog1.ShowDialog() != DialogResult.Cancel) { try { pck.SaveAs(new FileInfo(@"" + saveFileDialog1.FileName)); recentsToolStripMenuItem1.AddRecentItem(@"" + saveFileDialog1.FileName); } catch (Exception) { DialogResult reminder = MessageBox.Show("Cannot save file, file opened in another program.\nClose it first! ", "Save Failed", MessageBoxButtons.OK); } } } } } } } 

这是我在textbox_textchanged事件filter的代码:我不知道这是否重要。

 DataView DV = new DataView(dt); string oks; if (comboBox1.SelectedIndex == 0) { oks = "ffrom"; } else if (comboBox1.SelectedIndex == 1) { oks = "office"; } else if (comboBox1.SelectedIndex == 2) { oks = "code"; } else { if (comboBox1.SelectedIndex == 3) { oks = "datein"; } else { oks = "dateout"; } } DV.RowFilter = string.Format( oks+ " LIKE '%{0}%'", textBox5.Text); this.dataGridView1.DataSource = DV; dataGridView1.ClearSelection(); 

find了! 我只是改变了这一点:

 ws.Cells["A2"].LoadFromDataTable(dt, true); 

对此:

 ws.Cells["A2"].LoadFromDataTable((this.maindgv.DataSource as DataTable).DefaultView.ToTable(), true); 

我真的不知道它是如何工作的,但我认为这是因为dt是将数据加载到DataGridView while (this.maindgv.DataSource as DataTable).DefaultView.ToTable()是当前DataGridView上显示的数据。 我不确定。