I am importing data from an Excel file and converting it into a DataSet, which I have working (kind of). The problem that I am having is that two fields are Dates in Excel but when I do the import they get turned into numbers and I am not sure how to get them back to dates. The last two columns are the columns that are dates (HDate & CDate).
This is the code
private void FillDatagrid()
{
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"\\Server01\Ins\Eligible.xls");
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
DataTable table = new DataTable("Employees");
table.Columns.Add("StoreID");
table.Columns.Add("EmpID");
table.Columns.Add("EmpName");
table.Columns.Add("Position");
table.Columns.Add("HDate");
table.Columns.Add("CDate");
int rowCount = xlRange.Rows.Count;
for (int i = 2; i <= rowCount; i++)
{
table.Rows.Add(
xlRange.Cells[i, 1].Value2.ToString(),
xlRange.Cells[i, 2].Value2.ToString(),
xlRange.Cells[i, 3].Value2.ToString(),
xlRange.Cells[i, 4].Value2.ToString(),
xlRange.Cells[i, 5].Value2.ToString(),
xlRange.Cells[i, 5].Value2.ToString());
}
DataSet ds = new DataSet();
ds.Tables.Add(table);
dataGrid.ItemsSource = ds.Tables["Employees"].DefaultView;
}
As far as I can tell a Value2 will only convert to a string.
Note #1 Although I am putting this data into a DataGrid in this sample I am not doing that in the actual code block. I just wanted to mention that so that it didn't seem like this could be fixed with formatting in XAML etc.
Note #2 I realize I have xlRange.Cells[i, 5].Value2.ToString() twice. I am doing so to get around the problem of column 6 have null values, which my import didn't like. I plan to come back to that after I get this problem fixed.
Note #3 When I say I am getting the date as a string I mean it is coming from Excel as a string but formatted as a number so, for instance, the cell data has a date like 6/30/2015 but it comes over to my dataset like 42185.