查询从c#中的excel表读取数据

时间:2012-09-05 08:52:15

标签: excel c#-4.0

感谢 Astander 回复我的查询

我在这里有更详细的查询。

        string cs = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + @"D:\\sample.xls;" + "Excel 12.0;HDR=YES;";
        OleDbConnection Excelcon = new OleDbConnection(cs);
        OleDbDataAdapter ad = new OleDbDataAdapter();
        ad.SelectCommand = new OleDbCommand("SELECT *FROM [Sheet1$]", Excelcon);
        DataTable dt = new DataTable();
        ad.Fill(dt);
        return dt;

我在select语句中遇到错误:

  

Microsoft Office Access数据库引擎找不到对象'Sheet1 $'。确保对象存在,并且您正确拼写其名称和路径名称。

希望有人能帮我找到解决方案。

2 个答案:

答案 0 :(得分:0)

对我有用的是, 创建文件时,它存储在某个特定位置。就我而言,C:/Documents

我手动将位置更改为D: 这就是我写的

  

string connStringExcel = @“Provider = Microsoft.ACE.OLEDB.12.0; Data Source = D:\ example.xls ; Extended Properties =”“Excel 12.0; HDR = YES “;”“;`

因此,实际路径应为

  

string connStringExcel = @“Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\ A \ Documents \ example.xls; Extended Properties =”“Excel 12.0; HDR = YES;”“”;`< / p>

所以在给出正确位置的路径时,我的查询已经解决了。

希望它也可以帮助别人。

答案 1 :(得分:0)

// 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();

参考thisLink

相关问题