Crear documentos notes a partir de un fichero txt

Espero me puedas echar una mano. Necesito importar los datos de un fichero txt a notes creando nuevos documentos. ¿Me puedes decir cómo puedo leer los registros del txt, para ir metiendo cada dato en su correspondiente campo del nuevo documento?.

1 Respuesta

Respuesta
1
Un ejemplillo...
' Asignamos el Path y extension de ficheros a abrir
path = Cstr(configPath(0))
pathName$ = path + Cstr(configExt(0))
Print "Abriendo todos los archivos de "+ pathName
' Abrimos ficheros
file$ = Dir$(pathName$, 0)
Do While file$ <> ""
'Iniciamos error en fichero a cierto, al encontrar alguna linea lo pone a falso,
' en caso de error de formato de linea rara salimos
hayError = True
lini = -1
Print "Abriendo archivo: " + path + file$
fin = Freefile()
Open (path + file ) For Input As #fin
' Tratamos cada linea de texto
Do While Not Eof(fin)
Line Input #fin,lin
lini = lini + 1
If (Trim(Cstr(lin)) <> Trim(cabecera$)) And (Trim(Cstr(lin)) <> "") Then
' Creamos la lista de valores de la linea ( separando por ";" y quitando las comillas (") )
llista=CarregarLlista(lin)
' Insertamos los valores en el documento que toca de forma ordenada
Call Tratar(llista, file)
If hayError = True Then
Goto fin
End If
End If
Loop
fin: Close #fin
Call crearDocLog( db, file, hayError, lini , lin, (path+file))
If hayError = False Then
'Eliminamos el archivo tratado
Kill (path + file)
Else
'Movemos el archivo tratado a .old
'Name (path + file) As (path + file + ".old")
'Eliminamos el archivo tratado
Kill (path + file)
End If
file$ = Dir$()
Loop
Function CarregarLlista (lin As String) As Variant
On Error Goto errCarregarLlista
'Quitamos las comillas del texto
lin=Replace(lin,|"|,||)
'Separamos la linea en una lista de elementos que estaban separados por ";"
CarregarLlista=Explode( lin,";",True)
Exit Function
errCarregarLlista:
Print "Error CarregarLlista: "+Error+" "+Cstr(Err)
CarregarLlista=Null
Exit Function
End Function
Sub Tratar ( llista As Variant, file As String )
' Si la linea es correcta y contiene MAX_VALORES elementos la tratamos
If longitud(llista) = MAX_VALORES Then
If formato_ok(llista) Then
Dim session As New NotesSession
Dim db As NotesDatabase
Dim doc As NotesDocument
Dim dc As NotesDocumentCollection
Dim Vista As NotesView
Dim data As Variant
Set db = session.CurrentDatabase
Set Vista = db.GetView( "(Busqueda Fecha)" )
'Recogemos variables fecha y hora ( son diferentes de las demas )
data = Explode(llista(0),"/",False)
fecha = Datevalue(Cstr(data(1))+"/"+Cstr(data(0))+"/"+Cstr(data(2)))
hora = Timevalue(llista(1))
Print "Tratando "+Cstr(fecha) +" , " + Cstr(hora)
' Buscamos un documento con la fecha pasada por la linea
Busqueda = fecha
Set dc = Vista.GetAllDocumentsByKey(Busqueda, False)
Set doc = dc.GetFirstDocument()
If doc Is Nothing Then
'Hay que crear un nuevo documento para el dia
Set doc = New NotesDocument( db )
doc.Form="F.DatosDiarios"
doc.dia= fecha
doc.lista_1= fecha
doc.lista_2 = hora
' Rellenamos los campos lista*, min*, max* y media*
For i = 3 To MAX_VALORES
Set item = doc.ReplaceItemValue( "lista_"+Cstr(i), Cdbl(llista(i-1)) )
Set item = doc.ReplaceItemValue( "min_"+Cstr(i), Cdbl(llista(i-1)) )
Set item = doc.ReplaceItemValue( "max_"+Cstr(i), Cdbl(llista(i-1)) )
Set item = doc.ReplaceItemValue( "media_"+Cstr(i), Cdbl(llista(i-1)) )
Next
'Ponemos el campo de autores
Set item = doc.AppendItemValue("Autores", "Anonymous" )
item.IsAuthors = True
Else
'Hay que modificar el documento del dia pasado por linea
doc.lista_1 = Arrayappend( doc.GetItemValue( "lista_1" ),fecha)
'Insertamos los nuevos valores al final
doc.lista_2 = Arrayappend( doc.GetItemValue( "lista_2" ),hora)
For i = 3 To MAX_VALORES
Set item = doc.ReplaceItemValue( "lista_"+Cstr(i), Arrayappend( doc.GetItemValue( "lista_" + Cstr(i)),Cdbl(llista(i-1))))
Next
' Comprovamos si la columna de fechas esta ordenada
indice_a_insertar = insertar_ordenado( doc, doc.GetItemValue( "lista_2" ), hora )
If ( indice_a_insertar <> -1 ) Then
'No estaba ordenada, Movemos una posición todos los elementos e insertamos el nuevo elemento donde le toca
For i = 2 To MAX_VALORES
Set item = doc.ReplaceItemValue( "lista_"+Cstr(i), Mover(indice_a_insertar,doc.GetItemValue( "lista_" + Cstr(i))))
Next
End If
' Calculamos el maximo, minimo y promedio de las listas
For i = 3 To MAX_VALORES
If i <> 8 Then
array = doc.GetItemValue("min_"+Cstr(i))
Set item = doc.ReplaceItemValue( "min_"+Cstr(i), Min(Cdbl(llista(i-1)), Cdbl(array(0))))
array = doc.GetItemValue("max_"+Cstr(i))
Set item = doc.ReplaceItemValue( "max_"+Cstr(i), Max(Cdbl(llista(i-1)), Cdbl(array(0))))
Set item = doc.ReplaceItemValue( "media_"+Cstr(i), Avg(doc.GetItemValue("lista_"+ Cstr(i))))
Else ' En la radiación solar no se tratan los ceros
array = doc.GetItemValue("min_"+Cstr(i))
Set item = doc.ReplaceItemValue( "min_"+Cstr(i), Min_Sin_Ceros(Cdbl(llista(i-1)), Cdbl(array(0))))
array = doc.GetItemValue("max_"+Cstr(i))
Set item = doc.ReplaceItemValue( "max_"+Cstr(i), Max(Cdbl(llista(i-1)), Cdbl(array(0))))
Set item = doc.ReplaceItemValue( "media_"+Cstr(i), Avg_Sin_Ceros(doc.GetItemValue("lista_"+ Cstr(i))))
End If
Next
End If
hayError = False
Call doc.Save(False,False)
Else
Print "La linea tratada no tiene valores validos "
hayError = True
Goto fin
End If
Else
Print "El documento no tiene un formato correcto en la linea de datos"
hayError = True
Goto fin
End If
fin:
End Sub
Function Replace(txt As String, s1 As String, s2 As String) As String
' Funcion para quitar las comillas (") que suele generar el Excel para designar elementos tipo texto
On Error Goto errReplace
Do While Instr(txt, s1) > 0
txt = Left$(txt, Instr(txt, s1)-1) + s2 + Right$(txt,Len(txt)-Instr(txt, s1))
Loop
Replace = txt
Exit Function
errReplace:
Replace = txt
Exit Function
End Function
Estas funciones te ayudarán a entender como se obtienen archivos de un directorio con LotusScript.
A partir de un path "C:\.." y un tipo de extensión "*.txt" por ejemplo, llamamos a la función Dir$ para obtener la lista de archivos, luego los tratamos uno a uno y los abrimos como InputFile, obteniendo Linea a Linea de los archivos.
Una vez tenemos la linea (suponemos que tenemos valores separados por comas) le pasamos un filtro (quitando comillas, etc) y generamos un ARRAY con todos los valores que usaremos para crear un nuevo documento.
Una vez hayamos tratado todas las líneas eliminamos el archivo con la sentencia kill.
Si tienes alguna duda dime algo...
Suerte!

Añade tu respuesta

Haz clic para o

Más respuestas relacionadas