Skip to content

Instantly share code, notes, and snippets.

@asquigglytwist
Last active April 4, 2018 09:13
Show Gist options
  • Save asquigglytwist/f8127292d3d29486ee2e4b287059ec94 to your computer and use it in GitHub Desktop.
Save asquigglytwist/f8127292d3d29486ee2e4b287059ec94 to your computer and use it in GitHub Desktop.
A gazillionth implementation of a CSV Parser in C#...
public string ToHTMLTable(string CSVFilePath, string tableCaption)
{
if (!File.Exists(CSVFilePath))
{
return "<div>--CSV file not found--</div>";
}
var sbHTable = new StringBuilder();
var curLine = string.Empty;
sbHTable.AppendFormat("<table><caption>{0}</caption>", tableCaption);
foreach (var line in File.ReadLines(CSVFilePath))
{
sbHTable.Append("<tr>");
var tokens = line.Split(new char[] { ',' }, StringSplitOptions.None);
for (long i = 0; i < tokens.LongLength; i++)
{
var token = tokens[i];
if (token.StartsWith("\"") && !token.EndsWith("\""))
{
var sbFullToken = new StringBuilder();
while(!tokens[i].EndsWith("\""))
{
sbFullToken.Append(tokens[i++]);
}
token = sbFullToken.ToString();
}
sbHTable.AppendFormat("<td>{0}</td>", string.IsNullOrWhiteSpace(token) ? "&mdash;" : token);
}
sbHTable.Append("</tr>");
}
sbHTable.Append("<tbody>");
sbHTable.Append("</tbody></table>");
return sbHTable.ToString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment