繁体   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