在VB.net中使用什么名字空间

编写一个vb.net脚本(作为SSIS ETL的一部分)将xls转换为tsv文件。我试图使用名称空间Imports Microsoft.Excel来包含下面的代码。但是,它显示没有这样的名称空间! 什么名称空间被包含在使用Excel打开closures并保存为function的一部分的vb.net oExcel.Workbooks.Open oBook.SaveAs(sTsvPath,-4158)

vb.net代码是

 Public Sub Main() Dim oExcel As Object Dim oBook As Object Dim sFileName As String Dim sFileNameOnly As String Dim sXlsPath As String Dim sTsvPath As String sFileName = CStr(Dts.Variables("User::Xls_File_Name").Value) sXlsPath = "H:\Xls_Files\" + sFileName sFileNameOnly = Path.GetFileNameWithoutExtension(sFileName) sTsvPath = "H:\Xls_Files\" + sFileNameOnly + ".Txt" oExcel = CreateObject("Excel.Application") oBook = oExcel.Workbooks.Open(sXlsPath) oBook.SaveAs(sTsvPath, -4158) oBook.Close(False) oExcel.Quit() Dts.TaskResult = ScriptResults.Success End Sub 

首先,您需要在“解决scheme资源pipe理器”窗格中添加对Microsoft Excel 15.0对象库的引用。 当您select“添加引用…”时,它会出现在COM对象选项卡中 – 您的版本号(例如15.0)可能会有所不同。

然后在代码中,您必须添加Imports Microsoft.Office.Interop.Excel ,如下所示:

 Option Infer On Option Strict On Imports System.IO Imports Microsoft.Office.Interop.Excel Module Module1 Sub Main() Dim srcDir = "C:\temp" Dim srcFilename = "somefile.xls" Dim destFile = Path.Combine(srcDir, Path.GetFileNameWithoutExtension(srcFilename) & ".txt") File.Delete(destFile) Dim excel As Application = Nothing Dim wb As Workbook = Nothing Try excel = New Application wb = excel.Workbooks.Open(Path.Combine(srcDir, srcFilename)) wb.SaveAs(destFile, XlFileFormat.xlCurrentPlatformText) Finally If wb IsNot Nothing Then wb.Close() End If If excel IsNot Nothing Then excel.Quit() End If ' see "The proper way to dispose Excel com object using VB.NET?" ' http://stackoverflow.com/a/38111107/1115360 for an explanation of the following: GC.Collect() GC.WaitForPendingFinalizers() GC.Collect() GC.WaitForPendingFinalizers() End Try End Sub End Module 

你将不得不添加在DTS相关的部分。

为简便起见Path.Combine(srcDir, Path.GetFileNameWithoutExtension(srcFilename) & ".txt")我使用了Path.Combine(srcDir, Path.GetFileNameWithoutExtension(srcFilename) & ".txt") ,而不是使用Path.GetExtensionPath.ChangeExtension ,你可以在更高质量的代码中使用。 此外,你应该包装在一个Try..CatchCatch适当的行动,以防万一出现问题。