簡體   English   中英

使用ADO.NET寫入空白Excel工作表

[英]Writing to a blank excel sheet with ADO.NET

我正在嘗試使用ADO.NET連接和寫入excel文件。 我用默認的Excel工作表創建了一個空白文件(我也嘗試過自定義工作表。)

由於某種原因,我無法將完整的數據行寫入工作表。 如果我創建一個新工作表它工作正常,但然后我有太多工作表,我無法刪除任何工作表。

將一行數據寫入空白表需要做些什么特別的事情嗎?

我嘗試做:

path= the path including my file. 

connString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=NO;\"", Server.MapPath(path));

dbCmd.CommandText = "Update  [Sheet1$] Set F1 = 'Col1', F2 = 'Col2', F3 = 'Col3', F4 = 'Col4'";
dbCmd.ExecuteNonQuery(); 

以下是創建全新電子表格,創建工作表(Sheet1)然后在其中插入行的示例。 這個例子的大部分是基於David Hayden的博客條目(這個任務的博客條目,btw !!)。

此外,您應該查看此Microsoft知識庫文章 ,以便從ADO.NET讀取/寫入Excel - 它真正涉及到很多細節。

    //Most of this code was from David Hayden's blog:
    // http://www.davidhayden.com/blog/dave/archive/2006/05/26/2973.aspx
    static void Main(string[] args)
    {
        string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Temp\TestSO1.xls;Extended Properties=""Excel 8.0;HDR=NO;""";
        DbProviderFactory factory =
          DbProviderFactories.GetFactory("System.Data.OleDb");

        using (DbConnection connection = factory.CreateConnection())
        {
            connection.ConnectionString = connectionString;
            using (DbCommand command = connection.CreateCommand())
            {
                connection.Open();  //open the connection

                //use the '$' notation after the sheet name to indicate that this is
                // an existing sheet and not to actually create it.  This basically defines
                // the metadata for the insert statements that will follow.
                // If the '$' notation is removed, then a new sheet is created named 'Sheet1'.
                command.CommandText = "CREATE TABLE [Sheet1$] (F1 number, F2 char(255), F3 char(128))";
                command.ExecuteNonQuery();

                //now we insert the values into the existing sheet...no new sheet is added.
                command.CommandText = "INSERT INTO [Sheet1$] (F1, F2, F3) VALUES(4,\"Tampa\",\"Florida\")";
                command.ExecuteNonQuery();

                //insert another row into the sheet...
                command.CommandText = "INSERT INTO [Sheet1$] (F1, F2, F3) VALUES(5,\"Pittsburgh\",\"Pennsylvania\")";
                command.ExecuteNonQuery();
            }
        }
    }

我發現的唯一問題是,即使連接字符串聲明不使用標題,您仍然必須為工作表定義列名,並且ADO.NET在創建具有行標題名稱的工作表時插入一行。 在插入所有內容並刪除第一行之后,我似乎無法找到解決方法。 不是很優雅。

希望這可以幫助!! 如果您有其他問題,請告訴我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM