简体   繁体   中英

How to read a Date column from excel to a string in c#?

I am writing a C# console application which reads data from Excel spreadsheet using the SmartXLS library. I am able to read all the other column data except the 'usage date'column. Kindly, suggest me a way to solve this problem.

Date column in Excel:

usage date

Oct-15
Oct-15
Oct-15

Function:

public void GetData()
        {

            int count = 0;

            DeskTokens = new List<Token>();

            string directory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            string path = Path.Combine(directory, @"C:\projects\Product_Usage_Year.xlsx");

            SmartXLS.WorkBook WB = new WorkBook();
            WB.readXLSX(path);

            DataTable dt = WB.ExportDataTable();

            string CurrentType = string.Empty;
            string CurrentCategory = string.Empty;

            DataRow dr;
            for (int i = 1; i < dt.Rows.Count; i++)
            {
                dr = dt.Rows[i];
                var tkn = new Token();

                tkn.Usagedate = dr[0].ToString(); //error in reading the date column
                tkn.Product_name = dr[1].ToString();
                tkn.Product_Version = dr[2].ToString();
                tkn.Userid = dr[3].ToString();
                tkn.User_name = dr[4].ToString();

                DeskTokens.Add(tkn);
                count++;
                Console.WriteLine("Read : " + count);

                Console.WriteLine("    Reading : " + tkn.Usagedate + "," + tkn.Product_name + "," + tkn.Product_Version + "," + tkn.Userid + "," + tkn.User_name);

            }
        }

Token Class:

 class Token

{
    public string Usagedate { get; set; }
    public string Product_name { get; set; }
    public string Product_Version { get; set; }
    public string Userid { get; set; }
    public string User_name { get; set; }
}

尝试使用DateTime.FromOADate方法在Excel和.net之间进行转换:

DateTime.FromOADate(Double.Parse(dr[0].ToString()));

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