将excel数据逐行渲染到网页(C#)

时间:2012-10-30 21:07:36

标签: c# asp.net excel webmatrix

有人可以帮助我使用WebMatrix 2逐行打印数据

我正在尝试使用excel 2007和/或2003最后一行DataGrid1无效。这是我尝试的第三天,请帮助。

String Excel = "C://TEST/test_2.xls";
String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Excel +";Extended Properties=Excel 8.0;";

string.System.Data.OleDb.OleDbConnection objConn = new`system.Data.OleDb.OleDbConnection(sConnectionString);`


objConn.Open();
System.Data.OleDb.OleDbCommand objCmdSelect = new System.Data.OleDb.OleDbCommand("SELECT * FROM [Sheet1$]", objConn);

System.Data.OleDb.OleDbDataAdapter objAdapter1 = new System.Data.OleDb.OleDbDataAdapter(objCmdSelect);

System.Data.DataSet objDataset1 = new System.Data.DataSet();

objAdapter1.Fill(objDataset1, "XLData");
objConn.Close();
int c = objDataset1.Tables[0].Columns.Count;
int count =0;

//For Test
Response.Write("Colums: "+objDataset1.Tables[0].Columns.Count.ToString()+"<br>");
Response.Write("Rows: "+objDataset1.Tables[0].Rows.Count.ToString()+"<br>");


// Bind data to DataGrid control. Following part not working, also i like to print data with for or foreach loop)

DataGrid1.DataSource = objDataset1.Tables[0].DefaultView;
DataGrid1.DataBind();
//Other option if Data.Grid does not work!!
change Rows to Columns to print Columns.
for (int i=0;i<r;i++){
for (int j=0;j<c;j++){
Response.Write(objDataset1.Tables[0].Rows[i].ItemArray[j]+" ");
}
Response.Write("<br>");
}

1 个答案:

答案 0 :(得分:1)

除了代码中的各种语法错误之外,您还创建了一个新的OleDbDataAdapter但未将其附加到任何内容中。我怀疑你的程序在Fill语句中抛出异常,因为它没有要执行的SQL命令。您需要将OleDataDbAdapter对象的实例化编辑为:

System.Data.OleDb.OleDbDataAdapter objAdapter1 = new System.Data.OleDb.OleDbDataAdapter(objCmdSelect);

另外,正如DJ KRAZE正确指出的那样,在代码顶部添加以下行将有助于您清理一些内容并使其更容易理解:

using System.Data;
using System.Data.OleDb;

我不确定您对循环中“打印”数据的评论意味着什么,但将数据绑定到DataGrid意味着您不必这样做。

修改

以下是改善循环的方法

foreach(DataRow row in objDataset1.Tables[0].Rows)
{
    foreach(DataColumn col in objDataset1.Tables[0].Columns)
    {
        Response.Write(row[col.ColumnName].ToString());
    }

    Response.Write(count++ + "<br>");
}