A | B | |
---|---|---|
1 | FirstName | LastName |
2 | Scott | Bishop |
3 | Katie | Jordan |
http://localhost/WebApplication1
将位置文本框中的文本替换为 http://localhost/ExcelCSTest,然后单击确定。此时将创建一个新项目,其中包括一个名为 WebForm1.aspx 的 Web 窗体。using System.Data.OleDb; using System.Data;
// Create connection string variable. Modify the "Data Source" // parameter as appropriate for your environment. String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Server.MapPath("../ExcelData.xls") + ";" + "Extended Properties=Excel 8.0;"; // Create connection object by using the preceding connection string. OleDbConnection objConn = new OleDbConnection(sConnectionString); // Open connection with the database. objConn.Open(); // The code to follow uses a SQL SELECT command to display the data from the worksheet. // Create new OleDbCommand to return data from worksheet. OleDbCommand objCmdSelect =new OleDbCommand("SELECT * FROM myRange1", objConn); // Create new OleDbDataAdapter that is used to build a DataSet // based on the preceding SQL SELECT statement. OleDbDataAdapter objAdapter1 = new OleDbDataAdapter(); // Pass the Select command to the adapter. objAdapter1.SelectCommand = objCmdSelect; // Create new DataSet to hold information from the worksheet. DataSet objDataset1 = new DataSet(); // Fill the DataSet with the information from the worksheet. objAdapter1.Fill(objDataset1, "XLData"); // Bind data to DataGrid control. DataGrid1.DataSource = objDataset1.Tables[0].DefaultView; DataGrid1.DataBind(); // Clean up objects. objConn.Close();
// Create connection string variable. Modify the "Data Source" // parameter as appropriate for your environment. String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Server.MapPath("../ExcelData.xls") + ";" + "Extended Properties=Excel 8.0;";正如注释中所描述的那样,必须修改特定 Excel 工作表的路径信息。此外,还必须设置 Extended Properties 参数的值,以便正确地连接到文件。
C 驱动器 - Inetpub - Wwwroot(其中包含 ExcelData.xls) - ExcelCSTest(包含 WebForm1.aspx)文件的 IIS 路径如下所示:
Web 根目录(其中包含 ExcelData.xls) - ExcelCSTest(包含 WebForm1.aspx)在本例中,WebForm1.aspx 页到 ExcelData.xls 文件的相对 路径为“../ExcelData.xls”。“../”字符通知 IIS 转到上一级文件夹。因此,代码
Server.MapPath("../ExcelData.xls")返回以下字符串:
C:\Inetpub\Wwwroot\ExcelData.xls
您无需使用 Server.MapPath。您也可以将此信息硬编码为一个特定的路径,或使用任何方法提供该 Excel 文件在硬盘上的位置。本文地址:http://com.8s8s.com/it/it44116.htm