使用 Jet 访问某些 Excel 工作表时出错
我正在使用 ASP.NET 打开服务器上托管的 Excel 2003 文档。 Excel 电子表格由我无法控制的系统生成,有 5 个命名工作表。我按如下方式访问每张纸中的数据(为了可读性而添加换行符):
string ExcelConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\sample.xls;
Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1;\";";
OleDbDataAdapter myData =
new OleDbDataAdapter("SELECT * FROM [mysheet]", ExcelConn);
myData.TableMappings.Add("Table", "mysheet");
myData.Fill(ExcelDS);
这适用于 5 张纸中的 3 张。另外两个抛出这个错误:
Microsoft Jet 数据库引擎 找不到对象“mysheet”。 确保该对象存在并且 你拼写它的名字和路径名 正确。
我通过检查底部选项卡中的文本以及检查在 Excel 中生成的字符串的末尾,对工作表名称进行了四重检查:
=CELL("filename")
c:\[sample.xls]mysheet
连接字符串指定一次并为所有 5 个工作表重复使用。
我是否需要使用与 Excel 中可见的名称不匹配的字符串来引用工作表?也许是隐藏的字符、空格等?还有其他方法可以找到该表的真实名称吗?对于检索此数据还有其他建议吗?
注意:我无法修改 Excel 文档(如果可以的话,我会使用 SSIS 导入 CSV)。
我正在使用.NET 3.5 / II6。
I am using ASP.NET to open an Excel 2003 document hosted on the server. The excel spreadsheet, produced by a system outside of my control, has 5 named worksheets. I access the data in each sheet as follows (line breaks added for readability):
string ExcelConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\sample.xls;
Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1;\";";
OleDbDataAdapter myData =
new OleDbDataAdapter("SELECT * FROM [mysheet]", ExcelConn);
myData.TableMappings.Add("Table", "mysheet");
myData.Fill(ExcelDS);
This works for 3 of the 5 sheets. The other two throw this error:
The Microsoft Jet database engine
could not find the object 'mysheet'.
Make sure the object exists and that
you spell its name and the path name
correctly.
I have quadruple-checked the sheet name by examining the text in the bottom tab and also by examining the end of the string that this produces in Excel:
=CELL("filename")
c:\[sample.xls]mysheet
The connection string is specified once and reused for all 5 sheets.
Is it possible that I need to reference the sheet with a string that doesn't match the name that is visible in Excel? Maybe hidden characters, spaces, etc.? Is there another way to find the true name of the sheet? Any other suggestions for retrieving this data?
Note: I cannot modify the Excel document (I would have used SSIS to import CSV if I could have it my way).
I'm using .NET 3.5 / II6.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,我找到了一种方法来揭示该表的实际名称。
使用问题中的连接字符串,我可以执行此操作...
打开连接后,我可以使用调试器来检索工作表名称。
我发现Excel文档中有10个工作表名称。导致错误的两张纸具有相似的名称,后缀有“$”。我认为我陷入了支持噩梦,因为我敢打赌有人在将 Excel 文档发送给我之前就已经玩过它 - 但至少我知道如何提取数据。
Well, I found a way to uncover the actual name of the sheet.
Using the connection string in the question, I can do this...
With the connection open, I can use the debugger to retrieve the sheet names.
I found that there were 10 sheet names in the Excel document. The 2 sheets that were causing errors had similar names post-fixed with a "$". I think I'm in for a support nightmare as I'm willing to bet someone played with the Excel document before sending it to me - but at least I know how to pull the data.