我正在尝试使用 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),然后在其中插入一行。这个例子的大部分内容是基于博客条目大卫·海登 http://www.davidhayden.com/blog/dave/archive/2006/05/26/2973.aspx(顺便说一句,对于这项任务来说,这是一篇很棒的博客文章!!)。
另外,你应该看看这个微软知识库文章 http://support.microsoft.com/kb/316934/en-us#12用于从 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 会插入一行。除了在插入所有内容并删除第一行后进入之外,我似乎找不到解决方法。不是很优雅。
希望这可以帮助!!如果您还有其他问题,请告诉我。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)