2017-09-27 93 views
1

如何使用EPPlus將過濾的數據從DataGridView導入到Excel中? 我不知道從哪裏開始,我還沒有發現任何類似於我的問題。如何使用EPPlus將過濾的DataGridView數據保存到Excel中?

這是我保存按鈕的代碼:

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事件過濾器的代碼: 我不知道這是很重要的。

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(); 
+0

發現這個:[鏈接](https://stackoverflow.com/questions/18126940/get-datatable-from-datagridview-respecting-filters-and-sorting)試圖轉換它以適應我的代碼,沒有工作 –

回答

1

找到了!我只是改變了這一點:

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

這樣:

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

我真的不知道它是如何工作的,但我認爲這是因爲dt是被裝載到DataGridView(this.maindgv.DataSource as DataTable).DefaultView.ToTable()的數據是數據目前顯示在DataGridView。雖然我不確定。

+0

您對數據的假設是正確的。這是我的答案的主要觀點,即通過'DataTable'將所有數據導出到Excel,同時傳遞'DataView.ToTable()'導出所有經過濾後的數據。對不起,如果在使用'ClosedXML'而不是'ExcelPackage'的所有額外細節中丟失了。 – OhBeWise

相關問題