title: Export a C# List of Lists to Excel
body: <p>Using C#, is there a direct way to export a List of Lists (i.e., <code>List&lt;List&lt;T&gt;&gt;</code>) to Excel 2003?</p>
  
  <p>I am parsing out large text files and exporting to Excel. Writing one cell at a time creates way too much overhead. I chose to use <code>List&lt;T&gt;</code> so that I would not have to worry about specifying the number of rows or columns.</p>
  
  <p>Currently, I wait until end of file, then put the contents of my <code>List&lt;List&lt;object&gt;&gt;</code> into a 2-dimensional array. Then the array can be set as the value of an Excel.Range object. It works, but it seems like I should be able to take my List of Lists, without worrying about the number of rows or columns, and just dump it into a worksheet from A1 to wherever.</p>
  
  <p>Here's a snippet of the code I'd like to replace or improve on:</p>
  
  <pre><code>object oOpt = System.Reflection.Missing.Value; //for optional arguments
  Excel.Application oXL = new Excel.Application();
  Excel.Workbooks oWBs = oXL.Workbooks;
  Excel._Workbook oWB = oWBs.Add(Excel.XlWBATemplate.xlWBATWorksheet);
  Excel._Worksheet oSheet = (Excel._Worksheet)oWB.ActiveSheet;
  
  int numberOfRows = outputRows.Count;
  int numberOfColumns = int.MinValue;
  
  //outputRows is a List&lt;List&lt;object&gt;&gt;
  foreach (List&lt;object&gt; outputColumns in outputRows)
  {
          if (numberOfColumns &lt; outputColumns.Count)
          { numberOfColumns = outputColumns.Count; }
  }
  
  Excel.Range oRng = oSheet.get_Range("A1", oSheet.Cells[numberOfRows,numberOfColumns]);
  
  object[,] outputArray = new object[numberOfRows,numberOfColumns];
  
  for (int row = 0; row &lt; numberOfRows; row++)
  {
          for (int col = 0; col &lt; outputRows[row].Count; col++)
          {
                  outputArray[row, col] = outputRows[row][col];
          }
  }
  
  oRng.set_Value(oOpt, outputArray);
  
  oXL.Visible = true;
  oXL.UserControl = true;
  </code></pre>
  
  <p>This works, but I'd rather use the List directly to Excel than having the intermediary step of creating an array just for the sake of Excel. Any ideas?</p>