我正在尝试阅读并将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>
如何执行此代码?
答案 0 :(得分:1)
您的代码尝试将数据绑定到GridView,但它们仅在Web Forms中可用。 cshtml文件是一种称为Web Pages的不同开发模型。 WebMatrix专为开发网页而设计。在Web页面中编写代码时,必须使用Razor syntax。相当于GridView的Web页面是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>