Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Importing from Excel for XLSX
Message
De
19/01/2015 16:50:28
 
 
À
Tous
Information générale
Forum:
ASP.NET
Catégorie:
Autre
Titre:
Importing from Excel for XLSX
Versions des environnements
Environment:
VB 9.0
OS:
Windows 8.1
Network:
Windows 2008 Server
Database:
MS SQL Server
Application:
Web
Divers
Thread ID:
01613933
Message ID:
01613933
Vues:
29
I use to have this class to import an Excel XLS file:
Imports System.Data.OleDb
Imports System.Text

Public Class Import

    Public cMessage As String = ""
    Public cSource As String = ""
    Public cWorkbook As String = "Sheet1"
    Public nCount As Integer = 0
    Public nDuration As Double = 0
    Public nLanguage As Integer = 1
    Public oDataAdapter As OleDbDataAdapter = Nothing
    Public oDataSet As DataSet = New DataSet
    Public oRows As DataRowCollection = Nothing
    Private cASheetCalledSchemaIsNotFound As String = ""
    Private cTheExcelSheetShouldBeInAXLSFormat As String = ""
    Private cTheFieldDoesNotExist As String = ""
    Private oApp As App = Nothing
    Private oConnection As OleDbConnection = Nothing
    Private oField As Collection = New Collection
    Private oProcess As LXProcess = Nothing

    ' This is when we access the class in a desktop mode
    Sub New(ByVal toApplication As App)
        oApp = toApplication
        nLanguage = oApp.nLanguage
        Initialize()
    End Sub

    ' This is when we access the class in a Web or Web Service mode
    Public Sub New(ByVal toProcess As LXProcess)
        oProcess = toProcess
        oApp = oProcess.oApp
        nLanguage = oProcess.nLanguage
        Initialize()
    End Sub

    ' Initialize
    Private Function Initialize() As Boolean

        ' Based on the language
        Select Case nLanguage

            ' English
            Case 1
                cASheetCalledSchemaIsNotFound = "A sheet called ""Schema"" is not found."
                cTheExcelSheetShouldBeInAXLSFormat = "The Excel sheet should be in a XLS format."
                cTheFieldDoesNotExist = "The field ##Field## does not exist in the Excel sheet."

                ' French
            Case 2
                cASheetCalledSchemaIsNotFound = "Une feuille appelée ""Schema"" est introuvable."
                cTheExcelSheetShouldBeInAXLSFormat = "Le fichier Excel doit être dans un format XLS."
                cTheFieldDoesNotExist = "Le champ ##Field## n'existe pas dans le fichier Excel."

                ' Spanish
            Case 3
                cASheetCalledSchemaIsNotFound = "No se ha encontrado una hoja llamada ""Schema""."
                cTheExcelSheetShouldBeInAXLSFormat = "El fichero Excel debe estar en formato XLS."
                cTheFieldDoesNotExist = "The field ##Field## does not exist in the Excel sheet."

                ' Portuguese
            Case 4
                cASheetCalledSchemaIsNotFound = "A sheet called ""Schema"" is not found."
                cTheExcelSheetShouldBeInAXLSFormat = "The Excel sheet should be in a XLS format."
                cTheFieldDoesNotExist = "The field ##Field## does not exist in the Excel sheet."

        End Select

        Return True
    End Function

    ' Import from Excel
    Public Function ImportFromExcel() As Boolean
        Dim lcConnection As String = ""
        Dim lcField As String = ""
        Dim lnDateNow As Double = 0
        Dim lnDateNow2 As Double = 0
        Dim lnElapse As Double = 0
        Dim loData As Data = Nothing
        Dim loLogData As LogData = Nothing
        Dim loObject As Object

        ' Get the proper definition as per the current scope
        If oProcess Is Nothing Then
            loData = New Data(oApp)
            loLogData = New LogData(oApp)
        Else
            loData = New Data(oProcess)
            loLogData = New LogData(oProcess)
        End If

        ' Reset the values
        cMessage = ""
        oRows = Nothing

        ' Start time
        lnDateNow = Date.Now.Ticks

        ' Initialization
        lcConnection = "provider=Microsoft.Jet.OLEDB.4.0; data source='" + cSource + "'; Extended Properties=Excel 8.0;"

        ' Assign the source directory
        oConnection = New OleDbConnection(lcConnection)

        ' Select the data from Sheet1 of the workbook
        oDataAdapter = New OleDbDataAdapter("Select * From [" + cWorkbook + "$]", oConnection)

        ' Try to import the data
        Try
            oDataAdapter.Fill(oDataSet)
        Catch loError As Exception
            cMessage = loError.Message

            ' Try to extrapolate
            Select Case cMessage

                ' External table is not in the expected format.
                Case "External table is not in the expected format."
                    cMessage = cTheExcelSheetShouldBeInAXLSFormat

                    ' 'Schema$' is not a valid name.  Make sure that it does not include invalid characters or punctuation and that it is not too long.
                Case "'Schema$' is not a valid name.  Make sure that it does not include invalid characters or punctuation and that it is not too long."
                    cMessage = cASheetCalledSchemaIsNotFound

            End Select

            Return False
        End Try

        ' Record count
        nCount = oDataSet.Tables(0).Rows.Count

        ' If we have some records
        If nCount > 0 Then

            ' Adjust to our default name
            oDataSet.Tables("Table").TableName = "Temp"

            oRows = oDataSet.Tables("Temp").Rows()

            ' If we have a field to verify for before proceeding
            If oField.Count > 0 Then

                ' For each field
                For Each loObject In oField

                    ' Initialization
                    lcField = Trim(loObject(1))

                    ' If the field does not exist
                    If Not loData.FieldExist(oDataSet, "Temp", lcField) Then
                        cMessage = oApp.StrTran(cTheFieldDoesNotExist, "##Field##", lcField)
                        Return False
                    End If

                Next

            End If

        End If

        ' End time
        lnDateNow2 = Date.Now.Ticks

        lnElapse = ((lnDateNow2 - lnDateNow) / 10000000)

        ' Just in case
        If lnElapse > 999.999 Then
            lnElapse = 999.999
        End If

        nDuration = lnElapse

        ' Add the log
        loLogData.cLog = "Select * From [" + cWorkbook + "$]" + oApp.cCR + oApp.cCR + _
         "Duration: " + oApp.GetFormatValue(nDuration, , 4) + " " + _
         "Count: " + nCount.ToString + oApp.cCR + oApp.cCR
        If Not loLogData.AddLog() Then
        End If

        Return True
    End Function

    ' Add a field in the collection which will be verified at first to make sure it is part of the Excel file
    ' expC1 Table
    Public Function AddField(ByVal tcField As String) As Boolean
        Dim lcField As String = ""
        Dim loObject(1) As Object

        ' Initialization
        lcField = Trim(tcField)

        ' Initialization
        loObject(1) = tcField

        oField.Add(loObject)

        Return True
    End Function

End Class
This approach no longer works for an XLSX.

Is there a way to fine tune that or I would need to consider a totally different approach?
Michel Fournier
Level Extreme Inc.
Designer, architect, owner of the Level Extreme Platform
Subscribe to the site at https://www.levelextreme.com/Home/DataEntry?Activator=55&NoStore=303
Subscription benefits https://www.levelextreme.com/Home/ViewPage?Activator=7&ID=52
Suivant
Répondre
Fil
Voir

Click here to load this message in the networking platform