Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Importing from Excel for XLSX
Message
De
21/01/2015 10:42:28
 
 
À
19/01/2015 16:50:28
Information générale
Forum:
ASP.NET
Catégorie:
Autre
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:
01614012
Vues:
33
This would then be my updated class for important data from Excel also supporting Flexcel. If you use Flexcel and do not wish to install Access, you may use an approach like this in regards to nImportMode=2. Note that this is based on the Jet import where it considers the first Excel row to be your field names. Then, the data starts on row 2. For me, as soon as I see a row starting with a blank, this is the end. Users are usually doing that to only import until a blank so they can preserve the rest of the data as is.
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 nImportMode As Integer = 1
    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 llFormatted As Boolean = True
        Dim lnColumn As Integer = 0
        Dim lnColumnFromIndex As Integer = 0
        Dim lnCounter As Integer = 0
        Dim lnCounter2 As Integer = 0
        Dim lnDateNow As Double = 0
        Dim lnDateNow2 As Double = 0
        Dim lnElapse As Double = 0
        Dim lnRow As Integer = 0
        Dim lnXF As Integer = 0
        Dim loData As Data = Nothing
        Dim loFileType As FileType = New FileType(oProcess)
        Dim loLogData As LogData = Nothing
        Dim loObject As Object
        Dim loRow As DataRow = Nothing
        Dim loValue As Object = Nothing
        Dim loTFormula As FlexCel.Core.TFormula = Nothing
        Dim loTRichString As FlexCel.Core.TRichString = Nothing
        Dim loXlsFile As FlexCel.XlsAdapter.XlsFile = Nothing

        ' 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

        ' Get the file type
        loFileType.cFile = cSource
        If Not loFileType.FileType() Then
        End If

        ' Based on the type
        Select Case loFileType.nNoFileType

            ' XLS
            Case 3

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

                ' XLSX
            Case 18

                ' For this to work, you need to install this:
                ' 2010 Office System Driver: Data Connectivity Components
                ' This is actually the Access Database engine
                ' You have two files:
                ' AccessDatabaseEngine.exe
                ' AccessDatabaseEngine_x64.exe

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

        End Select

        ' Based on the import mode
        Select Case nImportMode

            ' Microsoft.Jet.OLEDB.4.0 driver
            Case 1

                ' 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

                ' Flexcel
            Case 2

                ' This comes from the documentation D:\TMSSoftware\FlexCelNET\samples\vb\VS2013\Modules\10.API\20.Reading Files
                ' There is also another approach D:\TMSSoftware\FlexCelNET\samples\vb\VS2013\Modules\10.API\22.Virtual Mode
                ' The virtual mode shows a different way to import the files
                ' Instead of loading the full file into memory, it writes to the dataset as the file is being loaded
                ' The virtual mode uses less memory, but it is more complex to implement
                ' For small files having less than 10000 rows, it is better to use the code from the first approach

                ' Open the Excel file
                loXlsFile = New FlexCel.XlsAdapter.XlsFile(False)
                loXlsFile.Open(cSource)

                ' Initialization
                loXlsFile.ActiveSheet = 1

                ' Initialization
                lnColumn = loXlsFile.ColCount
                lnRow = loXlsFile.RowCount

                ' Create the dataset default table
                oDataSet.Tables.Add("Table")

                ' Add the columns in the dataset based on the first row
                For lnCounter = 1 To lnColumn
                    oDataSet.Tables(0).Columns.Add(loXlsFile.GetStringFromCell(1, lnCounter))
                Next

                ' For each row
                For lnCounter = 2 To lnRow

                    ' If this is a blank, we end
                    If loXlsFile.GetStringFromCell(lnCounter, 1).Length = 0 Then
                        Exit For
                    End If

                    ' Create a new record
                    loRow = oDataSet.Tables(0).NewRow

                    ' This loop will only loop on used cells
                    ' It is more efficient than looping on all the columns
                    ' Reverse the loop to avoid calling ColCountInRow more than once
                    For lnCounter2 = loXlsFile.ColCountInRow(lnCounter) To 1 Step -1

                        ' Initialization
                        lnColumnFromIndex = loXlsFile.ColFromIndex(lnCounter, lnCounter2)

                        ' If we want it formatted
                        If llFormatted Then
                            loTRichString = loXlsFile.GetStringFromCell(lnCounter, lnColumnFromIndex)
                            loRow(lnColumnFromIndex - 1) = loTRichString.Value
                        Else

                            ' This is the cell format, we will not use it here
                            loValue = loXlsFile.GetCellValueIndexed(lnCounter, lnCounter2, lnXF)

                            ' Initialization
                            loTFormula = TryCast(loValue, FlexCel.Core.TFormula)

                            ' If we have a formula
                            If Not loTFormula Is Nothing Then

                                ' When we have formulas, we want to write the formula result
                                ' If we wanted the formula text, we would not need this part
                                loRow(lnColumnFromIndex - 1) = Convert.ToString(loTFormula.Result)

                            Else
                                loRow(lnColumnFromIndex - 1) = Convert.ToString(loValue)
                            End If

                        End If

                    Next

                    oDataSet.Tables(0).Rows.Add(loRow)
                Next

        End Select

        ' 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

        ' Based on the import mode
        Select nImportMode

            ' Microsoft.Jet.OLEDB.4.0 driver
            Case 1
                loLogData.cLog = "Select * From [" + cWorkbook + "$]" + oApp.cCR + oApp.cCR + _
                 "Duration: " + oApp.GetFormatValue(nDuration, , 4) + " " + _
                 "Count: " + nCount.ToString + oApp.cCR + oApp.cCR

                ' Flexcel
            Case 2
                loLogData.cLog = "Flexcel" + oApp.cCR + oApp.cCR + _
                 "Duration: " + oApp.GetFormatValue(nDuration, , 4) + " " + _
                 "Count: " + nCount.ToString + oApp.cCR + oApp.cCR

        End Select

        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
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
Précédent
Répondre
Fil
Voir

Click here to load this message in the networking platform