i need to read data from some excel sheets. The data in the excel sheets is already formatted in such a way that i am able to get the desired data by using this method.
This is what i am doing:
using (var conn = new OleDbConnection(strBld.ToString()))
{
conn.Open();
IEnumerable<IDictionary<string, object>> excelDataRaw =
conn.Query("select * from [Curves$A:IT]").
Cast<IDictionary<string, object>>();
int i = 0;
string previousKey = null;
var curve = new List<IEnumerable<object>>();
var excelData = new Dictionary<string, IDictionary<object, object>>();
//var excelData = new Dictionary<string, IDictionary<string, decimal>>();
foreach (var key in excelDataRaw.Select(dictionary => dictionary.Keys).
ElementAt(i))
{
string key1 = key;
// gets the data from one column within the excel file
curve.Add(excelDataRaw.Select(col => col[key1]).
Where(row => row != null).ToList());
if (i % 2 == 0)
{
// store the column header
previousKey = key;
}
if (i % 2 == 1)
{
// merge the data from the first column (keys)
// with the data from the second column (values)
IEnumerable<object> keys = curve[i - 1];
IEnumerable<object> values = curve[i];
// cast works but than you can't zip the lists together
//IEnumerable<string> keys = curve[i - 1].Cast<string>();
//IEnumerable<decimal> values = curve[i].Cast<decimal>();
// zip them together on their index
var dic = keys.Zip(values, (k, v) => new { k, v }).
ToDictionary(x => x.k, x => x.v);
if (previousKey != null)
{
if (!excelData.ContainsKey(previousKey))
{
excelData.Add(previousKey, dic);
}
}
}
++i;
}
}
I extract all data from the excel file (excelDataRaw). i then select all data that belongs together into a list (curve) and combine two lists that belong to each other into a dictionary (dic). The final result is a dictionary (excelData) that contains the column head from the excel file as a key (previousKey) and the data relevant to this column head as a dictionary (dic).
I would like to cast the dictionary (excelData) from
Dictionary<string, IDictionary<object, object>>
into
Dictionary<string, IDictionary<string, decimal>>
but i can’t cast object into string or decimal and i can’t zip the lists together to get the dictionary (dic) after casting each list to the desired type. Has anyone an idea how to achieve the desired result(type)?
Well i found a solution, I must have overlooked the obvious yesterday. A good night of sleep helps sometimes :).