使用SSIS在Excel中删除单个工作表

由于一些并发问题,我不得不使用多张工作表创build一个工作簿。 在执行结束时,一些工作表会有数据,有些不会。 我使用执行SQL任务创build工作表。

我试图通过工作簿循环,并删除不超过一个单行的表。 换句话说,如果行数不大于1,就删除表单。这个问题的任何指针都会被理解。 请让我知道你是否需要我的问题的更多细节。 先谢谢你。

编辑

以下是我从MSDN获得的脚本任务。 我把它修改到可以到达Excel表格并计算行数的位置,现在我只想当count = 1时删除表格。 有人可以帮我吗?

using System; using System.Data; using Microsoft.SqlServer.Dts.Runtime; using System.Windows.Forms; using System.Data.OleDb; using System.IO; namespace ST_c346c80b4e6747688383c47a9f3e6f78.csproj { [System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")] public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase { #region VSTA generated code enum ScriptResults { Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success, Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure }; #endregion public void Main() { string count = ""; string fileToTest; string tableToTest; string connectionString; fileToTest = Dts.Variables["ExcelFile"].Value.ToString(); tableToTest = Dts.Variables["ExcelTable"].Value.ToString(); Dts.Variables["ExcelTableExists"].Value = false; connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + fileToTest + ";Extended Properties=Excel 8.0"; string SQL = "SELECT COUNT (*) FROM [" + tableToTest + "$]"; using (OleDbConnection conn = new OleDbConnection(connectionString)) { conn.Open(); using (OleDbCommand cmd = new OleDbCommand(SQL, conn)) { using (OleDbDataReader reader = cmd.ExecuteReader()) { reader.Read(); count = reader[0].ToString(); //if (count = 1) } } conn.Close(); } //return count; } } } 

编辑

在进一步的调查中,我发现我需要添加excel互操作程序集才能工作。 我没有这个select,因为这个解决scheme将被移植到140个不同的机器。

可悲的是你不能使用OLEDB在Excel中删除工作表,最好的办法是使用DROP表命令清除数据

 connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + fileToTest + ";Mode=ReadWrite;Extended Properties=Excel 8.0"; string SQL = "SELECT COUNT(*) FROM [" + tableToTest + "$]"; using (OleDbConnection conn = new OleDbConnection(connectionString)) { conn.Open(); using (OleDbCommand CountCmd = new OleDbCommand(SQL, conn)) { int RecordCount = (int)CountCmd.ExecuteScalar(); if (RecordCount == 1) { SQL = "DROP TABLE [" + tableToTest + "$]"; using (OleDbCommand DropCmd = new OleDbCommand(SQL, conn)) { DropCmd.ExecuteNonQuery(); } } } conn.Close(); } 

注意:使用Mode=ReadWrite 。 您可以包含/排除HDR=Yes/No但是如果您希望对工作簿进行读/写访问,则不得包含IMEX=1

顺便说一句:没有必要使用OleDbDataReader来读取单个标量结果,而是使用ExecuteScalar()。

唯一的解决办法是使用OleDB将要保留的数据复制到一个新的excel文件中,并replace原来的文件。 如果你这样做,你会失去任何公式或格式。