RDesai
RDesai

Reputation: 21

rendering Excel data into Webmatrix

I am trying to read and bind Excel into a webpage and here is my initial code. When I run it in browser, all it does is display the code but not execute it. Here is the code saved as chtml:

@{

}

<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Excel Read Test</title>
</head>
<body>    
        string ExcelFile = Server.MapPath("App_Data/Pending_Requests.xls");
       string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ExcelFile + ";Extended Properties=Excel 8.0;";

        using (OleDbConnection conn = new OleDbConnection(connString)) 
            { 
            using (OleDbCommand cmd = new OleDbCommand()) 
            { 
            cmd.Connection = conn; 
            cmd.CommandText = "SELECT * FROM [EAST]"; 
            conn.Open(); 
            OleDbDataReader dr = cmd.ExecuteReader(); 
            GridView1.DataSource = dr; 
            GridView1.DataBind(); 
            conn.Close(); 
            } 
            }
   </body>

How can I execute this code?

Upvotes: 2

Views: 1031

Answers (1)

Mike Brind
Mike Brind

Reputation: 30110

Your code tries to bind the data to a GridView, but they are only available in Web Forms. The cshtml files are a different development model known as Web Pages. WebMatrix is designed for developing Web Pages. When you write code in Web Pages, you have to use Razor syntax. The Web Pages equivalent to a GridView is the WebGrid. This is how to get your code working in the cshtml file:

@{
     var connString = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=|DataDirectory|Pending_Requests.xls;Extended Properties=Excel 8.0;";
     var provider = "System.Data.OleDb";
     var sql =  "SELECT * FROM [EAST$]";
     var db = Database.OpenConnectionString(connString, provider);
     var data = db.Query(sql);
     var grid = new WebGrid(data);
}

<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Excel Read Test</title>
</head>
    <body>    
       @grid.GetHtml()
    </body>
</html>

Upvotes: 1

Related Questions