2012-07-16 10 views
5

Estoy construyendo un proyecto y entiendo que Excel 2003 admite la importación de datos de páginas web externas a través de "Datos -> Importar datos externos -> Nueva consulta web".Importar datos a Excel 2003 con una página de inicio de sesión

Esto se puede hacer a través de los pocos pasos que se indican aquí: http://www.internet4classrooms.com/excel_import.htm

Sin embargo, el sitio que estoy importación de datos desde una página web interna (Intranet) y requiere un inicio de sesión cada vez que puedo acceder a él.

El sitio web no recuerda la contraseña y cada vez que presiono el botón "importar", no hace nada debido al inicio de sesión.

¿Cómo solicito un nombre de usuario + contraseña e inicio de sesión en el sitio web mientras importo los datos de un sitio web externo en Excel 2003?

+0

¿Es posible para usted para cambiar el código en el servidor de intranet? – seeker

+0

¿Qué tipo de datos es? ¿Puedes entenderlo de otra manera? ¿Puedes usar MSXML o la automatización de IE para recuperarlo? ¿Esta respuesta ayuda? http://stackoverflow.com/a/11216467/190829 – JimmyPena

Respuesta

2

Me encontré con esto hace aproximadamente un año y como sugirió JimmyPena, la automatización de IE es probablemente el camino a seguir. Esto se verá mucho más complicado de lo que esperabas, pero créanme, pasé horas tratando de encontrar una manera más simple y no pude encontrar una.

Tómese su tiempo para aprender sobre HTML y el objeto DOM. Puede parecer excesivo para lo que está haciendo pero le resultará útil en el futuro si desea obtener datos de los sitios web. Aquí hay un script para conseguir que apunta en la dirección correcta:

  1. Crear un formulario de usuario con dos cuadros de texto y un botón
  2. Cuadrodetexto1 será la entrada de nombre de usuario y TextBox2 será su contraseña
  3. Usted debe enmascarar la contraseña entrada seleccionando un carácter de contraseña en la ventana de propiedades (Presione F4 en el Editor de VBA, seleccione textbox2 del menú desplegable e ingrese un carácter junto a PasswordChar)
  4. Haga doble clic en el botón que acaba de crear y pegue el siguiente código:

    Option Explicit 
    
    Private Sub CommandButton1_Click() 
    Const READYSTATE_COMPLETE = 4 
    Const tempDir As String = "C:\Windows\Temp\" 
    
    Dim userName$, passWord$, URL$, s_outerhtml$ ''These are strings 
    Dim IE As Object, IE_Element As Object, IE_HTMLCollection As Object 
    Dim i_file% ''This is an integer 
    Dim blnUsernameEntered As Boolean, blnPasswordEntered As Boolean, blnSheetFnd As Boolean 
    Dim ws As Excel.Worksheet 
    
    ''Test for missing username or password 
    If Me.TextBox1 = vbNullString Then MsgBox "Enter a User Name", vbOKOnly, "User Name Missing": Exit Sub 
    If Me.TextBox2 = vbNullString Then MsgBox "Enter a Password", vbOKOnly, "Password Missing": Exit Sub 
    
    ''Set the username and password based on the userform inputs 
    userName = Me.TextBox1.Value 
    passWord = Me.TextBox2.Value 
    
    ''Hide the form 
    Me.Hide 
    
    ''Enter your address to navigate to here 
    URL = "http://theofficialjbfansite.webs.com/apps/auth/login" 
    
    ''Create an Internet Explorer object if it doesn't exist 
    If IE Is Nothing Then Set IE = CreateObject("InternetExplorer.Application") 
    
    ''Make the window visible with true, hidden with false 
    IE.Visible = True 
    ''navigate to the website 
    IE.Navigate URL 
    
    '' use this loop to make wait until the webpage has loaded 
    Do While IE.Busy Or IE.readyState <> READYSTATE_COMPLETE 
        DoEvents 
    Loop 
    
    ''This is where it will get tricky - see my notes on DOM at the end of this post 
    ''build a collection of input elements 
    Set IE_HTMLCollection = IE.document.getElementsByTagName("input") 
    ''for each html element in the "input" collection 
    For Each IE_Element In IE_HTMLCollection 
        If IE_Element.Name = "email" Then IE_Element.innerText = userName: blnUsernameEntered = True 
        If IE_Element.Name = "password" Then IE_Element.innerText = passWord: blnPasswordEntered = True 
        If blnUsernameEntered = True And blnPasswordEntered = True Then Exit For 
        ''Unblock line below if you are having trouble finding the element name, 
        ''view the output in the Immediate Window (Ctrl + G in the VBA Editor) 
        ''Debug.Print IE_Element.Name 
    Next 
    
    ''Find the form and submit it 
    Set IE_HTMLCollection = IE.document.getElementsByTagName("form") 
    For Each IE_Element In IE_HTMLCollection 
        If IE_Element.Name = "loginForm" Then IE_Element.submit 
    Next 
    
    Do While IE.Busy Or IE.readyState <> READYSTATE_COMPLETE 
        DoEvents 
    Loop 
    
    ''The next line helps ensure that the html has been fully loaded 
    Application.Wait Now() + TimeValue("0:00:02") 
    s_outerhtml = IE.document.body.OuterHtml 
    i_file = FreeFile 
    
    
    ''This is a modification of some code I found at www.tek-tips.com <--great resource 
    ''the code saves a temporary copy of the webpage to your temp file 
    Open tempDir & "\tempFile.htm" For Output As #i_file 
    Print #i_file, s_outerhtml 
    
    Close #i_file 
    
    ''Creating a "Data" sheet if it doesn't exist 
    For Each ws In ThisWorkbook.Worksheets 
        If ws.Name = "Data" Then blnSheetFnd = True: Exit For 
    Next 
    
    If blnSheetFnd = False Then Sheets.Add: ActiveSheet.Name = "Data" 
    
    Sheets("Data").Cells.Clear 
    
    ''Here is your webquery, using the temporary file as its source 
    ''this is untested in 2003, if it errors out, record a macro 
    ''and replace the property that throws the error with your recorded property 
    With Sheets("Data").QueryTables.Add(Connection:= _ 
        "URL;" & tempDir & "tempFile.htm" _ 
        , Destination:=Range("$A$1")) 
        .Name = "Data" 
        .FieldNames = True 
        .RowNumbers = False 
        .FillAdjacentFormulas = False 
        .PreserveFormatting = True 
        .RefreshOnFileOpen = False 
        .BackgroundQuery = True 
        .RefreshStyle = xlInsertDeleteCells 
        .SavePassword = False 
        .SaveData = True 
        .AdjustColumnWidth = True 
        .RefreshPeriod = 0 
        .WebSelectionType = xlEntirePage 
        .WebFormatting = xlWebFormattingAll 
        .WebPreFormattedTextToColumns = True 
        .WebConsecutiveDelimitersAsOne = True 
        .WebSingleBlockTextImport = False 
        .WebDisableDateRecognition = False 
        .WebDisableRedirections = False 
        .Refresh BackgroundQuery:=False 
    End With 
    
    ''delete the temporary file 
    Kill tempDir & "\tempFile.htm" 
    
    ''clean up after yourself, foo!! 
    IE.Quit 
    Set IE = Nothing 
    Set IE_HTMLCollection = Nothing 
    Unload UserForm1 
    
    End Sub 
    
  5. cambiar la URL de su sitio web y modificar los métodos getelement para trabajar con su página web

La parte más difícil para alguien no familiarizado con HTML y el DOM (Document Object Model) será encontrar la correcta elementos en la página.

Un buen truco es usar la Herramienta de desarrollo de Internet Explorer. Abra su página de intranet en IE y presione F12. Esto abrirá la herramienta de desarrollador. Haga clic en el icono de flecha (la flecha apunta hacia arriba y hacia la izquierda) en la barra de herramientas y vuelva a la página de intranet. Pase el cursor sobre la página y verá cuadros azules pintados alrededor de cada elemento. Desplácese sobre el nombre de usuario y haga clic en el cuadro de entrada. Esto resaltará el HTML en el código fuente.

Desde aquí puede identificar el elemento id, nombre, nombre de etiqueta y clase si tiene uno. Investigue un poco en getelementbyID, getelementsbytagname, etc. o siga el código anterior para tener una idea de cómo funciona.

Una última nota, si su página de intranet tiene un elemento de formulario, tendrá que obtener el objeto de formulario con los métodos getelement arriba y enviarlo con .submit. Si la página utiliza un objeto de botón, obtenga el elemento del botón y use .click. ¡Buena suerte!

0

No estoy seguro de si todavía es relevante, pero tengo una solución para esto a través de una macro

Los siguientes son los pasos:

1: Registre su macro en la importación de la nueva consulta web (nada lo hará)

2: Actualice todas sus consultas.

Edite su consulta web para incluir nombre de usuario/contraseña en línea.

A continuación es mi macro:

Sub xmlUpdate() 
'This will enable the import of our XML data. The first part is a dummy import, to authenticate the Excel file with the iJento servers. The second part (Web_Query_1 is the actual import) 
'The sheet is initially inserted as "Dummy" and then promptly deleted. 
    Sheets.Add.Name = "Dummy" 
    ActiveWorkbook.XmlImport URL:= _ 
     "https://USERNAME:[email protected]/query/app?service=file=201" _ 
     , ImportMap:=Nothing, Overwrite:=True, Destination:=Range("$A$1") 
    Sheets("Dummy").Select 
    Application.DisplayAlerts = False 
    ActiveWindow.SelectedSheets.Delete 
    ActiveWorkbook.XmlMaps("Web_Query_1").DataBinding.Refresh 
    End Sub 

Cuestiones relacionadas