Friends, C# noob here, so apologies in advance!
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.
public static string ToCSV(this DataTable table)
{
var result = new StringBuilder();
for (int i = 0; i < 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 < table.Columns.Count; i++)
{
result.Append(row[i].ToString());
result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
}
}
return result.ToString();
}
This works fine if the Excel file is clean. Like this:
However, 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.
Like this:
I've tried doing this like this and checking the length of the row etc...
if (String.IsNullOrWhiteSpace(row[i].ToString()))
{
continue;
}
... but it breaks the structure of the file.
Question; what am I doing wrong?! I feel like I'm so close, but its just not behaving.
Thank you in advance for your assistance.