Last active
April 4, 2018 09:13
-
-
Save asquigglytwist/f8127292d3d29486ee2e4b287059ec94 to your computer and use it in GitHub Desktop.
A gazillionth implementation of a CSV Parser in C#...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) ? "—" : 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