This one should be simple, but I don’t really know how to find a way to do it…
I am using .NET 4.0. I have an object[12] filled with decimal numbers, and want to use it to fill an Excel range of Doubles [1,12]. I am converting JSON using JavaScriptSerializer:
JavaScriptSerializer javascriptSerializer = new JavaScriptSerializer();
var jsonData = javascriptSerializer.Deserialize<dynamic>("{data:[0.11, 0.12, 0.13, 0.14, 0.15, 0.16, 0.17, 0.18, 0.19, 0.2, 0.21, 0.22]}");
It should be a one-liner, but the only working thing I can come up with is:
var myArray = new Double[1, 12];
// the cast to Double is necessary as json data is of type decimal, however excel seems to only accepts Double here
for (int i = 0; i < 12; i++) { PrimeShr[0,i] = (Double) jsonData["data"][i]; };
// sheet is of type Microsoft.Office.Interop.Excel.Worksheet
sheet.Range["myExcelRangeName"].Value2 = myArray;
or still rather pitiful, but at least in one line:
sheet.Range["Input_PremiumSHR"].Value2 = new Double[1, 12] { { (Double)jsonData["data"][0], (Double)jsonData["data"][1], (Double)jsonData["data"][2], (Double)jsonData["data"][3], (Double)jsonData["data"][4], (Double)jsonData["data"][5], (Double)jsonData["data"][6], (Double)jsonData["data"][7], (Double)jsonData["data"][8], (Double)jsonData["data"][9], (Double)jsonData["data"][10], (Double)jsonData["data"][11] } };
I’d expect something like that to work, but from what I gather initializers won’t work this way :
sheet.Range["Input_PremiumSHR"].Value2 = new Double[1, 12] { new System.Collections.ArrayList( jsonData["data"] ).ToArray() };
I have quite a few similar cases (one with [12,1] which probably could be harder) and I don’t want to struggle with each one that much. Is there a way to write it a bit more simpler?
You can create an extension method that turns a single-dimensional array (or any other collection) into a 2D array with one column:
Using that you can write the code like this:
You could write that on one line, but I think that would hurt readability.