我在代码中确保填充当前日期值时遇到错误'string' does not contain a definition for 'ToDateTime'
。以下是代码:
public class LegalTransactionRec
{
public string AccountNumber { get; set; }
public string CostAmount { get; set; }
public string SSN { get; set; }
public int BatchID { get; set; }
public Attorney Attorney { get; set; }
public DateTime TransactionDate { get; set; }
public string Description { get; set; }
public int TransactionCode { get; set; }
}
它就在这里:
TransactionDate = Form1.CheckDate(xlRange.Cells[i, 2].Value2.ToDateTime())
这是检查以确保填充字段的函数:
public static DateTime CheckDate(DateTime tranDate)
{
DateTime date;
if (tranDate == null)
{
throw new System.ArgumentException("Value cannot be null", "original");
}
else
{
date = tranDate;
}
return date;
}
编辑:xlRange的代码:
try
{
//workbook = excelApp.Workbooks.Open(txtbxFilename.Text); View above comment
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.get_Item(1);
Microsoft.Office.Interop.Excel.Range xlRange = worksheet.UsedRange;
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
for (int i = 1; i <= rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{
lstTran.Add(new LegalTransactionRec()
{
AccountNumber = Form1.CleanString(xlRange.Cells[i, 1].Value2.ToString()),
CostAmount = Form1.TryToParse(Form1.CleanAmount(xlRange.Cells[i, 3].Value2.ToString())),
SSN = Form1.CleanString(xlRange.Cells[i, 6].Value2.ToString()),
TransactionDate = Form1.CheckDate(xlRange.Cells[i, 2].Value2.ToDateTime()),
Description = xlRange.Cells[i, 8].Value2.ToString(),
TransactionCode = xlRange.Cells[i, 4].Value2.ToInt() //Work on the CheckNull function later
});
}
}
}
非常感谢任何帮助。
答案 0 :(得分:3)
好吧,Value2包含一个字符串,简单明了。你想使用这样的东西:
static DateTime ConvertToDateTime(object obj)
{
if (obj == null)
throw new ArgumentNullException();
return (DateTime)obj;
}
然后只需致电
ConvertToDateTime(xlRange.Cells[i, 2].Value);
获取日期时间。
或者,如果Value
仍然返回字符串,则可以执行
static DateTime ConvertToDateTime(string str)
{
if (string.IsNullOrEmpty(str))
throw new ArgumentNullException();
return DateTime.Parse(str);
}
您可能必须这样称呼它:
ConvertToDateTime(xlRange.Cells[i, 2].Value as string);