C# Excel 文件 OLEDB 读取 HTML IMPORT

标签 c# .net html excel oledb

我必须为财务部自动化一些事情。我有一个 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/

相关文章:

.net - FTPWebRequest 和 AS/400 - 将 NAMEFMT 设置为 1

c# - silverlight工具包中的AutoCompleteBox for windows phone错误显示

php - 我的 HTML 表单使用 PHP 和 MySQL 无法正常工作

c# - 防止人们对我的网络协议(protocol)进行逆向工程

c# - 将日期格式解析为特定文化

c# - 如何处置 MemoryStream 对象

javascript - 如何更改 &lt;input/> 的占位符颜色?

html - div 内的内联 p 标签

c# - WCF 错误 : There was an error reading from the pipe: Unrecognized error 109 (0x6d)

c# - 类似于字典的数据结构,但有范围?