缺少读取生成的Excel文件的行

时间:2013-07-11 20:42:20

标签: c# excel ms-office oledb

我正在使用OleDB创建一个Excel文件,它工作得很好,接下来,我直接在Office Excel中向文件添加行,之后,当我尝试再次使用OleDB读取文件时,我手动添加的行不会出现,只有我在创建文件时写的列和行。

以下是代码:

//Creation of the file
        String connectionString = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=" + path + "; Mode=ReadWrite; Extended Properties= 'Excel 8.0; HDR=Yes; IMEX=0'";
        OleDbConnection oledbconnection;

        oledbconnection = new OleDbConnection(connectionString);
        oledbconnection.Open();

        String query = "CREATE TABLE [Sheet1] (....) ";

        OleDbCommand cmd = new OleDbCommand(query, oledbconnection);
        cmd.ExecuteNonQuery();

        oledbconnection.Close();

它运行正常,文件创建正确,然后,当我尝试修改它后读取文件时,我这样做

        String connectionStringRead = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=" + path + "; Extended Properties= 'Excel 8.0; HDR=Yes; IMEX=1'";

        OleDbConnection oledbconnection;
        oledbconnection = new OleDbConnection(connectionStringRead);
        oledbconnection.Open();

        DataTable table = new DataTable();
        String sheetName;

        sheetName = oledbconnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString();

        OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [" + sheetName + "]", oledbconnection);
        adapter.Fill(table);

        oledbconnection.Close();
        return table;

该表仅包含原始信息,而不包含我使用MS Excel添加的行。

我不明白这一点,你能帮帮我吗?

提前致谢

1 个答案:

答案 0 :(得分:1)

以前不要尝试,但如果

sheetName = "Sheet1" '-------> or whatever

应该是

OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [" + sheetName + "$]", oledbconnection);