Search code examples
libreofficelibreoffice-writer

Mail merge with Libre Office using .net


I have following code block which is working perfectly for OpenOffice SDK to automate Mail merge functionality.

    Public Function runQueryOnDataSource(ByVal nameOfdDtaource As String, ByVal query As String) As Boolean
    strLog = strLog + vbCrLf + Now.ToString() + ": runQueryOnDataSource nameOfdDtaource:" + nameOfdDtaource + ",query:" + query + "-Started"
    Dim oDB As Object, oBase As Object
    Dim oStatement As Object
    Dim rSQL As String
    Dim oRequete As Object
    Dim oServiceManager As Object, CreateUnoService As Object
    Try
        'Creation instance Open office
        oServiceManager = CreateObject("com.sun.star.ServiceManager")
        CreateUnoService = oServiceManager.createInstance("com.sun.star.sdb.DatabaseContext")
        mxMSFactory = (uno.util.Bootstrap.bootstrap()).getServiceManager()
        oDB = CreateUnoService.getByName(nameOfdDtaource) 'oDB=XDataSource
        'Connection
        oBase = oDB.getConnection("", "")   'oBase=XConnection
        oStatement = oBase.createStatement  'XStatement
        'rSQL = "SELECT * FROM ""26_MailMergeResult_DEMO"
        rSQL = query
        oRequete = oStatement.execute(rSQL)
        Return True
    Catch ex As Exception
        strLog = strLog + vbCrLf + Now.ToString() + ": Exception" + ex.ToString()
        Throw ex
    Finally
        oDB = Nothing
        oBase.Close()
        oBase.Dispose()
    End Try
    strLog = strLog + vbCrLf + Now.ToString() + ": runQueryOnDataSource-Finished"
    Return True
End Function

Above code is used to insert data into the DataSource already registered with libre office.But Now when I try to use it, line oServiceManager = CreateObject("com.sun.star.ServiceManager") generates error "Error Creating ActiveX object". Do anyone have idea, How do I fix this.


Solution

  • This code does not look right, so I'm surprised it ever worked. In other examples, the bootstrap() line always goes first. Then use that service manager instead of a separate oServiceManager variable.

    For example, see the Java code at https://www.openoffice.org/udk/common/man/spec/transparentofficecomponents.html.

    EDIT:

    You're almost there. The getByName() method returns uno.Any, which has a property called Value that DirectCast can use.

    Dim oDB As XDataSource
    Dim oBase As XConnection = Nothing
    Dim xContext As XComponentContext = uno.util.Bootstrap.bootstrap()
    Dim xMSFactory As XMultiServiceFactory = DirectCast(
        xContext.getServiceManager(), XMultiServiceFactory)
    Dim xNameAccess As XNameAccess = DirectCast(
        xMSFactory.createInstance("com.sun.star.sdb.DatabaseContext"), XNameAccess)
    oDB = DirectCast(xNameAccess.getByName("Bibliography").Value, XDataSource)
    oBase = DirectCast(oDB.getConnection("", ""), XConnection)