如何将日期列从 excel 读取到 c# 中的字符串?
How to read a Date column from excel to a string in c#?
我正在编写一个 C# 控制台应用程序,它使用 SmartXLS 库从 Excel 电子表格中读取数据。我能够读取除“使用日期”列之外的所有其他列数据。请建议我解决此问题的方法。
Excel 中的日期列:
使用日期
Oct-15
Oct-15
Oct-15
函数:
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);
}
}
令牌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()));
我正在编写一个 C# 控制台应用程序,它使用 SmartXLS 库从 Excel 电子表格中读取数据。我能够读取除“使用日期”列之外的所有其他列数据。请建议我解决此问题的方法。
Excel 中的日期列:
使用日期
Oct-15
Oct-15
Oct-15
函数:
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);
}
}
令牌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()));