我正在尝试格式化 Excel 2010 文档并且文件创建良好并且数据在那里,但是当脚本任务去格式化文件时它被损坏。我还注意到它只会读取 2 个工作表中的第一个。这是代码:
Dim lintLastRow As Integer
Dim lstrLastCol, lstrHeader As String
Dim mobjWorkbook As Workbook
Dim mappExcel As New Microsoft.Office.Interop.Excel.Application
Dim lobjWorksheet As Worksheet
Dim emptyBytes(0) As Byte
Dim oldCI As System.Globalization.CultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture
System.Threading.Thread.CurrentThread.CurrentCulture = New System.Globalization.CultureInfo("en-US")
Try
mappExcel.Visible = False
mappExcel.DisplayAlerts = False
mappExcel.AskToUpdateLinks = False
mappExcel.AlertBeforeOverwriting = False
mobjWorkbook = mappExcel.Workbooks.Open(Dts.Variables("FilePath").Value + Dts.Variables("FileName").Value)
mobjWorkbook.RefreshAll()
Dts.Log("worksheet count: " & mobjWorkbook.Sheets.Count, 0, emptyBytes)
For Each lobjWorksheet In mobjWorkbook.Sheets
If lobjWorksheet.Name = "Compare" Then
lstrLastCol = "T"
lstrHeader = "- Compare Results"
Else
lstrLastCol = "H"
lstrHeader = "- Trans UnMatch"
End If
'Dts.Log("Set worksheet: " & lintCount, 0, emptyBytes)
'lobjWorksheet = mobjWorkbook.Sheets.Item(lintCount)
Dts.Log("worksheet select", 0, emptyBytes)
lobjWorksheet.Select()
lobjWorksheet.Range("A1").Select()
If lobjWorksheet.Cells(2, 1).value = Nothing Then
lintLastRow = 4
Else
lobjWorksheet.Application.Cells.End(XlDirection.xlDown).Select()
lintLastRow = lobjWorksheet.Application.ActiveCell.Row + 2
End If
Dts.Log("last row: " & lintLastRow, 0, emptyBytes)
lobjWorksheet.Rows(1).Insert(XlInsertShiftDirection.xlShiftDown, False)
lobjWorksheet.Rows(1).Insert(XlInsertShiftDirection.xlShiftDown, False)
lobjWorksheet.Cells(1, 1).value = "PAM - GL Portfolio Level " + lstrHeader + " for " + Today
lobjWorksheet.Range("A1", lstrLastCol + "1").Merge()
lobjWorksheet.Range("A1").RowHeight = 27
lobjWorksheet.Range("A1", lstrLastCol + "3").Font.Bold = True
lobjWorksheet.Range("C4", lstrLastCol & lintLastRow).NumberFormat = "0.00" ' = FormatNumber("#####.00").
lobjWorksheet.Range("A3", lstrLastCol & lintLastRow).EntireColumn.AutoFit()
lobjWorksheet.Range("A1", lstrLastCol & lintLastRow).Font.Name = "Arial"
lobjWorksheet.Range("A1").Select()
Dts.Log("Complete Update", 0, emptyBytes)
Next
mobjWorkbook.Sheets("Compare").Select()
Dts.TaskResult = ScriptResults.Success
Catch ex As Exception
Dts.Events.FireError(0, "Format Excel Failed: ", _
ex.Message & ControlChars.CrLf & ex.StackTrace, _
String.Empty, 0)
Dts.TaskResult = ScriptResults.Failure
Finally
System.Threading.Thread.CurrentThread.CurrentCulture = oldCI
mobjWorkbook.Save()
mobjWorkbook.Close()
ReleaseCom(lobjWorksheet)
ReleaseCom(mobjWorkbook)
mappExcel.Quit()
ReleaseCom(mappExcel)
GC.Collect()
GC.WaitForPendingFinalizers()
End Try
这在我的机器和试验环境上运行良好。当它投入生产时,事情会迅速走下坡路。关于我所缺少的任何想法都会很棒。
谢谢