[英]Querying an Excel File from C# - No Results
我一直在尝试使用OLEDB连接从C#查询Excel文件。 程序运行时没有运行时错误,但不返回任何结果。 我用不同的excel文件尝试过,但是得到了相似的结果。
编辑:Excel文件位于项目目录中。 如果我从当前位置删除excel文件,程序将得到一个找不到文件的异常。
private void btnRun_Click(object sender, EventArgs e)
{
string strFileName = "playerData.xls";
string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strFileName + ";Extended Properties=" + "\"Excel 8.0;HDR=YES\"";
OleDbConnection conn = new OleDbConnection(connStr);
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM [Sheet1$]";
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
dgsResults.DataSource = ds;
conn.Close();
}
有谁知道为什么没有返回结果?
谢谢,
您在connStr中使用strFileName,但尚未提供路径。
应该遵循以下原则:
string strFileName = @"c:\excel location\playerData.xls";
显然,在数据绑定过程中必须引用特定的数据表。 在fill()方法解决问题后,添加以下行。
da.Fill(ds);
dgsResults.DataSource = ds.Tables[0]; //this is the line to be added
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.