简体   繁体   English

无法使用C#从我的Excel文件中读取

[英]Can't read from my Excel file using C#

I have an Excel 2007 file "my.xlsx" and a sheet named "States", and I have the following code 我有一个Excel 2007文件“ my.xlsx”和一个名为“ States”的工作表,并且我有以下代码

 using (OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\my.xlsx;Extended Properties='Excel 12.0 Xml;HDR=NO'"))
        {
            OleDbCommand cmd = new OleDbCommand("select * from [States]", con);

            con.Open();
            OleDbDataReader reader = cmd.ExecuteReader();
            while(reader.Read())
                Console.WriteLine(reader[0]);
        }

It keeps throwing exception saying "The Microsoft Office Access database engine could not find the object 'States'. Make sure the object exists and that you spell its name and the path name correctly.". 它不断抛出异常,说“ Microsoft Office Access数据库引擎找不到对象'States'。请确保该对象存在并且您正确拼写了它的名称和路径名。”。

Could someone help to see what's wrong with my code please? 有人可以帮忙看看我的代码有什么问题吗?

I know this may be not exactly what you want to hear, but you're in a long line of people who have had struggles trying to read excel files by using oledb... 我知道这可能不完全是您想听到的,但是您在一排排的人中很难通过使用oledb来读取Excel文件...

I've had a lot more luck using libraries such as NPOI to read Excel files from C#: 使用NPOI之类的库从C#中读取Excel文件的运气还很多:

http://npoi.codeplex.com/ (recommended) http://npoi.codeplex.com/ (推荐)

http://nexcel.sourceforge.net/ http://nexcel.sourceforge.net/

http://sourceforge.net/projects/koogra/ http://sourceforge.net/projects/koogra/

I think that you need to open the connection before creating the command - not sure if it's a big deal... 我认为您需要在创建命令之前打开连接-不确定这有什么大不了的...

Then add a $ at the end of the sheet name: 然后在工作表名称的末尾添加一个$

OleDbCommand cmd = new OleDbCommand("select * from [States$]", con);

Basically [Name] refers to a named range, whereas [Name$] refers to a sheet. 基本上[Name]指的是命名范围,而[Name$]指的是图纸。

For more information see this KB: http://support.microsoft.com/kb/316934 有关更多信息,请参见以下知识库文章: http : //support.microsoft.com/kb/316934

I just got it working by visiting this page 我只是通过访问此页面使其工作

http://www.davidhayden.com/blog/dave/archive/2006/05/26/2973.aspx http://www.davidhayden.com/blog/dave/archive/2006/05/26/2973.aspx

For my requirement, I only need to read an Excel file. 对于我的要求,我只需要读取一个Excel文件。 Most of the solutions I searched show you to use some kind of library, which is overkill for me. 我搜索的大多数解决方案都表明您使用某种类型的库,这对我来说太过分了。 I was really looking for someone to just post a code snippet on how to read the file, but I only found that on the page I put the link with. 我确实在寻找可以发布有关如何读取文件的代码段的人,但是我只在放置链接的页面上找到了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM