【问题标题】:What name space to use in VB.net在 VB.net 中使用什么命名空间
【发布时间】:2017-05-27 23:13:31
【问题描述】:

编写 vb.net 脚本(作为 SSIS ETL 的一部分)将 xls 转换为 tsv 文件。我试图使用该名称 空格Imports Microsoft.Excel 包含以下代码。但是,它显示没有 这样的命名空间!使用 Excel 打开关闭并另存为时要包含的名称空间 作为 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

【问题讨论】:

  • 您是否尝试搜索“vb.net excel 命名空间”?提示:你想要 Interop 的。
  • 是的,Microsoft.Office.Interop.Excel 命名空间只适用于Microsoft office,不适用于vb
  • 这不是 .Net 内置的。您必须在机器上安装 Excel,并且必须使用互操作程序集打开一个 excel 实例并告诉它执行您想要的操作。是的,这确实意味着实际启动 Excel。

标签: excel vb.net ssis


【解决方案1】:

首先,您需要在“解决方案资源管理器”窗格中添加对 Microsoft Excel 15.0 对象库的引用。当您选择“添加引用...”时,它会出现在 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.GetExtensionPath.ChangeExtension,您可以使用质量更好的代码。此外,您应该将File.Delete 包装在Try..Catch 中,并在Catch 中使用适当的操作,以防万一出现问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-22
    • 2020-11-24
    • 2011-12-10
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多