title: C# Convert Excel to CSV and Ignore Empty Cells
body: <p>Friends, C# noob here, so apologies in advance!</p>
  
  <p>I have the following method which loops over my Excel workbook sheet as a data table converting it to CSV via the string builder output.</p>
  
  <pre><code>    public static string ToCSV(this DataTable table)
      {
          var result = new StringBuilder();
          for (int i = 0; i &lt; table.Columns.Count; i++)
          {
              result.Append(table.Columns[i].ColumnName);
              result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
          }
  
          foreach (DataRow row in table.Rows)
          {
              for (int i = 0; i &lt; table.Columns.Count; i++)
              {
                  result.Append(row[i].ToString());
                  result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
              }
          }
          return result.ToString();
      }
  </code></pre>
  
  <p>This works fine if the Excel file is clean. Like this:</p>
  
  <p><a href="https://i.stack.imgur.com/uZ39K.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uZ39K.png" alt="enter image description here"></a></p>
  
  <p><strong>However</strong>, if you add any sort of formatting or anything to the Excel file the C# method treats the cells as having content in and outputs them to the CSV file.</p>
  
  <p>Like this:</p>
  
  <p><a href="https://i.stack.imgur.com/1LJam.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1LJam.png" alt="enter image description here"></a></p>
  
  <p>I've tried doing this like this and checking the length of the row etc... </p>
  
  <pre><code>if (String.IsNullOrWhiteSpace(row[i].ToString()))
  {
   continue;
  }
  </code></pre>
  
  <p>... but it breaks the structure of the file.</p>
  
  <p>Question;  what am I doing wrong?! I feel like I'm so close, but its just not behaving.</p>
  
  <p>Thank you in advance for your assistance.</p>