简体   繁体   中英

Export data from excel file (with a date column) to DataGrid using SmartXLS

I've successfully exported data from excel to datagrid through the following code:

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();
        }
    }
}

The ExportDataTable has 6 parameters, as you can see. The last parameter is true which means it should check if the column is of datetime type. So I don't get why I'm still getting the wrong output. Am I missing something?

Here's a screenshot (The Column4 should be of DateTime format :(): Column4应该为DateTime格式:(

I figured the DateTime format only works if each value in the column (in the excel file itself) is in date format. I guess there's no other way but to delete everything that is not in date format.

I know this question is a little old, but this worked for me, and it may help others...

I get the value of the cell in the datagrid view, as a string

string val = "";
if (dgv.Rows[rowCount].Cells[colCount].Value != null)
    val = dgv.Rows[rowCount].Cells[colCount].Value.ToString();

then I check to see if it is a date

DateTime dt = IsDate(val);

if (dt.Year != 1900)
    val = dt.ToString("yyyy/MM/dd");

If the function returns a date that the year is not 1900, then pass the date in yyyy/mm/dd format to the string, and then use the string as the cell value.

xlRange.Value2 = val;

here's the function... pretty simple, but like i say, it worked for me.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM