我必须为财务部自动化一些事情。我有一个 Excel 文件,我想使用 OleDb 读取它:
string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=A_File.xls;Extended Properties=""HTML Import;IMEX=1;""";
using (OleDbConnection connection = new OleDbConnection())
{
using (DbCommand command = connection.CreateCommand())
{
connection.ConnectionString = connectionString;
connection.Open();
DataTable dtSchema = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if( (null == dtSchema) || ( dtSchema.Rows.Count <= 0 ) )
{
//raise exception if needed
}
command.CommandText = "SELECT * FROM [NameOfTheWorksheet$]";
using (DbDataReader dr = command.ExecuteReader())
{
while (dr.Read())
{
//do something with the data
}
}
}
}
通常 connectionstring
会有一个扩展属性“Excel 8.0”,但文件无法以这种方式读取,因为它似乎是一个重命名为 .xls 的 html 文件。
当我将数据从 xls 复制到新的 xls 时,我可以使用 E.P. 读取新的 xls。设置为“Excel 8.0”。
是的,我可以通过创建 Excel 实例来读取文件,但我宁愿不...... 知道如何使用 OleDb 读取 xls 而无需手动更改 xls 或在实例化 Excel 中使用范围吗?
问候,
米歇尔
最佳答案
我在另一个论坛上问过同样的问题并得到了答案,所以我想我应该在这里分享它。根据这篇文章:http://ewbi.blogs.com/develops/2006/12/reading_html_ta.html
您必须在不带 $ 的 select 语句中使用页面标题,而不是使用工作表名称。从 [HTMLPageTitle] 中选择 *
关于C# Excel 文件 OLEDB 读取 HTML IMPORT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1238473/