用ADO.NET写一个空白的Excel表
我正在尝试使用ADO.NET连接并写入一个Excel文件。 我用默认的Excel表格创build了一个空白文件(我也试过用自定义表格)。
出于某种原因,我无法将一整行数据写入工作表。 如果我创build一个新的工作表,它工作正常,但是,我有太多的工作表,我无法删除任何工作表。
有没有什么特别的,你需要做一个数据写入一张白纸?
我试着做:
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();
以下是创build全新电子表格,创build工作表(Sheet1),然后在其中插入一行的示例。 这个例子中的大部分都是基于David Hayden的博客文章(这个任务很棒的博客,btw !!)。
此外,你应该看看这个微软知识库文章从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(); } } }
我发现的唯一问题是,即使连接string状态不使用标题,您仍然必须为您的工作表定义列名称和ADO.NET插入行时创build具有行标题名称的工作表。 我似乎无法find一种解决办法,除了插入所有内容并删除第一行之后。 不是很优雅。
希望这可以帮助!! 如果您有其他问题,请告诉我。
- 使用OleDbConnection :: GetOleDbSchemaTable()列出Excel表
- 我的代码读取Excel文件错误
- 使用ADO 3.5将数据从Excel导入到64位应用程序中
- 间歇性问题 – OleDbConnection.Open()抛出System.Data.OleDb.OleDbException:未指定的错误
- 该字段太小,无法接受您尝试添加的数据量。 有没有人从ADO.NET得到这个错误?
- 如何将DataTable插入(绑定)到Excel工作簿(VS Excel 2010工作簿项目)
- 有没有更好的方法来指出Excel中的“空值”?
- 如何在导入Excel中select以哪个行开头的数据库
- 如何在Excel中使用ADO.NET托pipe提供程序?