如何使用已应用过滤器的 closedXML 导出数据网格视图?

问题描述

我有两个问题。第一个问题是在我导出到 excel 时过滤行后,它为我提供了所有未应用过滤器的数据。

第二个是如何用b/n两个日期过滤? ```(dgvEmployeeList.DataSource as DataTable).defaultview.RowFilter = string.Format("date ?????);

DataGridView 过滤器

 private void btnSearchEmployeeType_Click(object sender,EventArgs e)
        {
            string searchValue = cbSearchByEmployeeType.Text;
            try
            {
               (dgvEmployeeList.DataSource as DataTable).defaultview.RowFilter = string.Format("EmployeeType  like '%" + searchValue + "%'");
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }

导出 DataGridView

 private void btnExportExcel_Click(object sender,EventArgs e)
        {
            using ( XLWorkbook workbook = new XLWorkbook())
              {

                workbook.Worksheets.Add((dgvEmployeeList.DataSource as DataTable),"Employees");// here is the problem 
                 workbook.SaveAs(sfd.FileName);
                 MessageBox.Show("You Have Successfully Exported your Data to an Excel File","Message",MessageBoxButtons.OK,MessageBoxIcon.information);
              }
        }

任何帮助!谢谢

解决方法

要设置带有日期的 RowFilter,请用 # 字符将日期值字符串括起来。为避免当前文化格式出现问题,日期带有 ToString() 以确保过滤器解析器能够理解它。请参阅下面的 PoC。


[TestMethod]
public void MyTestMethod()
{
    var dt = new DataTable();
    dt.Columns.Add(new DataColumn("dt",typeof(DateTime)));
    dt.Rows.Add(new object[] { new DateTime(1999,01,01) });
    dt.Rows.Add(new object[] { new DateTime(2000,02,01) });
    dt.Rows.Add(new object[] { new DateTime(2001,03,01) });
    dt.Rows.Add(new object[] { new DateTime(2002,04,01) });

    var startDate = new DateTime(2000,01);
    var endDate = new DateTime(2001,01);

    // use date strings between # signs and 
    // formatted via current culture to be sure it is parseable
    dt.DefaultView.RowFilter = $"dt >= #{startDate}# AND dt <= #{endDate}#";

    var r = dt.DefaultView.ToTable();
    Assert.IsTrue(r.Rows
        .Cast<DataRow>()
        .Select(i => (DateTime)i[0])
        .All(j => j >= startDate && j <= endDate));
}