2

我正在尝试读取 Excel 并将其绑定到网页中,这是我的初始代码。当我在浏览器中运行它时,它所做的只是显示代码而不是执行它。这是保存为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>

如何执行此代码?

4

1 回答 1

1

您的代码尝试将数据绑定到 GridView,但它们仅在Web Forms中可用。cshtml 文件是一种不同的开发模型,称为网页。WebMatrix 是为开发网页而设计的。当您在网页中编写代码时,您必须使用Razor 语法。与 GridView 等效的网页是 WebGrid。这是让您的代码在 cshtml 文件中工作的方法:

@{
     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>
于 2012-11-12T20:16:29.050 回答