我得到了一個使用Microsoft.Office.Interop.Excel [11.0.0.0]導入和導出文件的舊項目。在服務器MS Excel必須運行導入/導出工作。通過運行我的意思是有人必須登錄服務器,並通過開始菜單打開Excel(是的,這是不好的!)。有誰知道爲什麼需要保持開放?導入/導出非常脆弱,需要一天兩次關閉並重新打開,因爲它不斷崩潰。Office.Interop.Excel - 爲什麼需要在服務器上打開Excel?
這裏是代碼,被警告......這太可怕了!
objExcelApp = New Excel.Application()
objExcelApp.DisplayAlerts = False
objExcelBook = objExcelApp.Workbooks.Open(strExcelFileName, Password:="")
If objExcelBook.Sheets.Count > 0 Then
objExcelWorkSheet = CType(objExcelBook.Sheets(1), Excel.Worksheet)
objExcelWorkSheet.Name = gstrDEFAULTSHEETNAME 'Rename the sheet
objExcelRangeHeader = CType(objExcelWorkSheet.Rows(1), Excel.Range)
objExcelWorkSheet.Cells.Interior.ColorIndex = Excel.XlColorIndex.xlColorIndexNone
objExcelRangeFormat = objExcelWorkSheet.UsedRange
intColumn = objExcelRangeFormat.Columns.Count
For intColumnCount = 1 To intColumn
objColumnRange = CType(objExcelRangeHeader.Columns(intColumnCount), Excel.Range)
objColumnRange.EntireColumn.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.White)
objColumnRange.EntireColumn.ClearFormats()
objColumnRange.EntireRow.ClearFormats()
Next
With objExcelWorkSheet
.Name = gstrSHEET_EXCEL
.Rows.Range("1:1").Font.Bold = True
.Rows.Range("1:1").Font.Color = RGB(0, 0, 255)
.StandardWidth = 50
.Cells.WrapText = True
.EnableOutlining = True
End With
End If
objCountLink = CType(objExcelBook.LinkSources(), Object)
If Not IsNothing(objCountLink) Then
If (objCountLink.ToString.Length > 0) Then
lblErrorMessage.Visible = True
lblErrorMessage.InnerHtml = "<li> The spreadsheet you trying to import contains external links. Please ensure all links have been removed before attempting to import </li>"
objExcelBook.Close()
objExcelApp.Workbooks.Close()
objExcelApp.Quit()
objExcelApp = Nothing
Exit Sub
End If
End If
objExcelBook.Save() 'Save the excel
objExcelBook.Close()
objExcelApp.Workbooks.Close()
objExcelApp.Quit()
objExcelApp = Nothing
附註:確保你已經看到並閱讀[注意事項服務器端自動化Office](http://support.microsoft.com/kb/257757/)... – 2015-03-02 18:29:00
爲什麼這個問題標記爲C#示例代碼是Visual Basic? – phoog 2015-03-02 18:29:38
對不起,隊友,不習慣使用VB :) – Funky 2015-03-02 18:31:13