C# 使用SmartXLS将数据从excel文件(带有日期列)导出到DataGrid

C# 使用SmartXLS将数据从excel文件(带有日期列)导出到DataGrid,c#,wpf,excel,datagrid,smartxls,C#,Wpf,Excel,Datagrid,Smartxls,我已通过以下代码成功地将数据从excel导出到datagrid: using System; using System.Data; using System.Windows; using System.Windows.Data; using SmartXLS; namespace Calibration_Trial { /// <summary> /// Interaction logic for MainWindow.xaml /// </summ

我已通过以下代码成功地将数据从excel导出到datagrid:

using System;
using System.Data;
using System.Windows;
using System.Windows.Data;
using SmartXLS;


namespace Calibration_Trial
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            WorkBook m_book = new WorkBook();
            m_book.readXLSX("trial.xlsx");

            //Read data from spreadsheet.
            DataTable mbooktable = m_book.ExportDataTable(9, 0, 4, 4, false, true);


            simpleDataGrid.ItemsSource = mbooktable.AsDataView();
        }
    }
}
ExportDataTable有6个参数,如您所见。最后一个参数为true,这意味着它应该检查列是否为datetime类型。所以我不明白为什么我仍然得到错误的输出。我错过什么了吗

下面是一个屏幕截图,第4列应为DateTime格式:

我认为只有当excel文件中列中的每个值都是日期格式时,DateTime格式才有效。我想除了删除所有非日期格式的内容外,没有其他方法了。☹

我知道这个问题有点老了,但这对我来说很有效,它可能会帮助其他人

我在datagrid视图中以字符串的形式获取单元格的值

string val = "";
if (dgv.Rows[rowCount].Cells[colCount].Value != null)
    val = dgv.Rows[rowCount].Cells[colCount].Value.ToString();
然后我检查是否是约会

DateTime dt = IsDate(val);

if (dt.Year != 1900)
    val = dt.ToString("yyyy/MM/dd");
如果函数返回的日期不是1900年,则将yyyy/mm/dd格式的日期传递给字符串,然后将该字符串用作单元格值

xlRange.Value2=val

这是函数。。。很简单,但就像我说的,这对我很有效

private DateTime IsDate(string toCheck)
{
    DateTime dt = new DateTime();
    if (DateTime.TryParse(toCheck, out dt))
        dt = DateTime.Parse(toCheck);
    else
        dt = DateTime.Parse("1900/01/01");

    return dt;
}