下面的腳本任務將從每個工作表文件中刪除前2行(你需要在SSIS創建變量「ExcelFilePath」,並把它傳遞給任務,隨着'系統:: TASKNAME'):
public void Main()
{
MainTask();
GC.Collect();
GC.WaitForPendingFinalizers();
}
private void MainTask()
{
xl.Application xlApp = null;
xl.Workbook excelFile = null;
string excelFilePath = Dts.Variables["User::ExcelFilePath"].Value.ToString();
string thisTask = Dts.Variables["System::TaskName"].Value.ToString();
try
{
xlApp = new xl.Application();
excelFile = xlApp.Workbooks.Open(excelFilePath);
xlApp.DisplayAlerts = false;
foreach (xl.Worksheet ws in excelFile.Worksheets)
{
ws.Rows["1:2"].EntireRow.Delete();
}
xlApp.DisplayAlerts = true;
excelFile.Save();
excelFile.Close();
xlApp.Quit();
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (Exception ex)
{
Dts.Events.FireError(0, thisTask, ex.Message, String.Empty, 0);
if (excelFile != null) excelFile.Close(SaveChanges:false);
if (xlApp != null) xlApp.Quit();
}
}
您需要將引用添加到 'COM'> 'Microsoft Excel中[版本號]對象庫'(你有哪個版本)和 '.NET'>「微軟.CSharp」。然後,您需要在'Namespaces'區域聲明using xl = Microsoft.Office.Interop.Excel;
。