Note that there are some explanatory texts on larger screens.

plurals
  1. POPopulating 3 columns in an excel sheet from C#, without having repeated values across rows
    primarykey
    data
    text
    <p>Sorry if the question title was a bit weird. I want to populate 500 excel rows with a composite primary key which consists of 3 columns. 2 columns automatically generate random int between 1 and 50 and third is a date between 01.01.2006 and 31.12.2013. So i want to have 500 rows, each with a different combination of the 3. Here's my code</p> <pre><code> Type excelType = Type.GetTypeFromProgID("Excel.Application"); dynamic excel = Activator.CreateInstance(excelType); excel.visible = true; excel.Workbooks.Add(); Random rnd = new Random(); dynamic sheet = excel.ActiveSheet; for (int i = 1; i &lt;= 500; i++) { sheet.Cells[i, "A"] = rnd.Next(1,50); sheet.Cells[i, "B"] = rnd.Next(1,50); sheet.Cells[i, "C"] = RandomDay(); </code></pre> <p><strong>//</strong> this is where I'd check if a combination exists and if it does assign a new one</p> <pre><code> for (int j = 0; j &lt;= i + 1; j++) { if ( sheet.Cells[j + 1, "A"] == sheet.Cells[i, "A"] &amp;&amp; sheet.Cells[j + 1, "B"] == sheet.Cells[i, "B"] &amp;&amp; sheet.Cells[j + 1, "C"] == sheet.Cells[i, "C"]) { sheet.Cells[i, "A"] = rnd.Next(1,50); sheet.Cells[i, "B"] = rnd.Next(1,50); sheet.Cells[i, "C"] = RandomDay(); } } } } </code></pre> <p>// random date method</p> <pre><code> public static DateTime RandomDay() { DateTime start = new DateTime(2006, 1, 1); DateTime end = new DateTime(2013, 12, 31); Random gen = new Random(); int range = (end - start).Days; return start.AddDays(gen.Next(range)); } </code></pre> <p>I'm really not sure if this would work, plus it's running slow, it has to iterate over and over again to check if the combination exists. Does anyone have a better and faster solution? Thank you all!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload