tags:

views:

26

answers:

1

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.

+1  A: 

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.

Moo
Thanks @Moo. A code example would really help. I'm afraid I'm a PHP guy and I don't know much of anything about .NET.
skypanther
@skypanther - there you go :)
Moo
Thanks! I'll test it ... with my php version, I output to an HTML table then used a jQuery plug in to create a sortable, searchable table. That's my intent with the asp version -- I'm trying to add this to my woodworking club's web site but they use asp not php so I was a bit lost. Thanks!
skypanther