[英]How can I save filtered DataGridView data into Excel using EPPlus?
如何使用 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();
找到了! 我只是改變了這個:
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
上的數據。 我不確定。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.