skypanther
skypanther

Reputation: 995

ASP.net equivalent to PHP's fgetcsv to convert CSV to HTML table

I have the following PHP that reads in a CSV file and outputs rows/cells of an HTML table. Can someone help me with an ASP.net equivalent?

<?php
$f = fopen("spreadsheet.csv", "r");
while (($line = fgetcsv($f)) !== false) {
    if(trim($line) != '' && $line != "\n" && $line != "\r") {
        echo '<tr>';
        foreach ($line as $cell) {
            echo "<td>" . htmlspecialchars($cell) . "</td>";
        }
        echo "</tr>\n";
    }
}
fclose($f);
?>

I see various options like http://github.com/claco/csvdatareader/ but being clueless about ASP.net, I'm afraid I don't know how to make them work.

Upvotes: 0

Views: 1383

Answers (1)

user32826
user32826

Reputation:

As demonstrated below there is no need to go outside of the .Net core framework to handle CSV files - Visual Basics TextFieldParser class will do it for you with out external dependencies. You can even use it in C#!

StringBuilder MyTable = new StringBuilder();

var Parser = new TextFieldParser(@"C:\Path\To\File\File.csv");
Parser.HasFieldsEnclosedInQuotes = true;
Parser.SetDelimiters(",");
Parser.TextFieldType = FieldType.Delimited;
MyTable.AppendLine("<table>");

while(var Row = Parser.ReadFields()) 
{
    MyTable.AppendLine("<tr>");

    foreach(var Field in Row)
    {
        MyTable.AppendLine("<td>" + Field + "</td>");
    }

    Mytable.AppendLine("</tr>");
}

MyTable.AppendLine("</table>");

There is probably a few minor things wrong with the above, I'm doing it on the fly and very quickly :) It should be largely correct however - its a fairly OK code sample for an introduction, personally I wouldnt build the table myself but I would create a datasource (read the csv file into a datatable perhaps), and bind that to an ASP.Net control (HtmlTable or Gridview) which will build the html for us.

But in this case, its a nice example giving you exactly what you had in PHP.

Upvotes: 1

Related Questions