title: How to read Excel worksheets and write to a file asynchronously?
body: <p>I have been given a very large Excel workbook that contains 500+ sheets. Each sheet represents a store, and the rows contain transactions at that store. Each sheet layout is identical. I have been requested to write a program that loops through each sheet, pulls specific transaction data, and writes everything to one gigantic CSV file.</p>
  
  <p>I know that this kind of functionality is far better suited for relational database, but I have been asked to work on this as is.</p>
  
  <p>I have written a program that successfully parses the data and writes it. The problem is that it takes almost a half-hour to complete the file write when reading and writing data synchronously. </p>
  
  <p>I would like to accomplish this task by reading and writing the data from each sheet asynchronously. In C#, I would prefer to use the Task Parallel library for this, but am open to other options.</p>
  
  <p>I am thinking about spinning off the worker threads from a foreach loop, like so:</p>
  
  <pre><code>foreach( Worksheet ws in _excelApp.Worksheets)
  {
      Parallel.Invoke(()=&gt;ExportWorksheet(ws));
  }
  </code></pre>
  
  <p>And then in the method (shortened for brevity):</p>
  
  <pre><code>private void ExportWorksheet(Worksheet ws)
  {         
       using(FileStream fs = new new FileStream(fi.FullName, FileMode.Append, FileAccess.Write, FileShare.Write, 1, true))
       {
           for(int row = 1; row &lt; 300; row++)
           {
                for(int column = 1; column &lt; 20)
                {
                     byte[] bytes = Encoding.ASCII.GetBytes(ws.Cells[row, column].Value.ToString() + ",");
                     fs.Write(bytes, 0, bytes.count());
                }
  
                fs.Write(Encoding.ASCII.GetBytes("\n"), 0, 2);
           } 
       }
  
  }
  </code></pre>
  
  <p>This gives me strange results, of course.</p>
  
  <p>Am I on the right track? Should I be using a different encoding? Is there a cleaner way to accomplish the async write? Are there any threading rules being broken here? </p>
  
  <p>All suggestions are welcome. Thanks for the help.</p>