Exportar tabla a archivo de texto
Publicado por HSaenz (3 intervenciones) el 29/08/2023 18:01:53
Buen dia, tengo una tabla de sql que tengo que exportarla a un archivo de texto. ¿Como puedo hacer esto?
Gracias
Gracias
Valora esta pregunta


0
Private Sub HSaenz()
'' Los codigos que has enviado
'Dim Ob_DataSetRegTO As New DataSet '------ total de registros
'Dim OB_AdapterRegTO As New SqlClient.SqlDataAdapter("SELECT * FROM NominaTramitesivi ", conexion)
'OB_AdapterRegTO.Fill(Ob_DataSetRegTO, "TotalReg")
Dim Ob_DataSetRegTO As New DataSet '------ total de registros
' Mis pruebas estan hecho con Access, tienes que reemplazar OleDbDataAdapter por SqlClient.SqlDataAdapter
Dim OB_AdapterRegTO As New OleDbDataAdapter("SELECT * FROM NominaTramitesivi ", conexion)
OB_AdapterRegTO.Fill(Ob_DataSetRegTO, "TotalReg") ' Crea el DataTable llamado TotalReg en el DataSet Ob_DataSetRegTO
' Escribir los datos del DataTable "TotalReg" en un fichero
Dim FicheroAEscribir As System.IO.StreamWriter
Dim NombreFicheroAEscribir As String
' Para crear cada linea al formato CSV. El fichero puede ser leído con NotePad o con Excel (cuando seprador es ;).
Dim LineaTMP As String
Dim SeparadorSplit As Char() = {";"} ' ; es el saprador utilizado con XLS, pero puedes eligir otro.
' Es posible utilizar un SaveFileDialogBox para obtener el nombre y la ruta del fichero
' Pero, para mis pruebas, escribo el nombre del fichero como :
NombreFicheroAEscribir = CurDir() & "\" & "TotalReg" & ".CSV" ' Es la carpeta donde es el fichero EXE del programa
' Crear el fichero (reemplaza precedente si existe)
FicheroAEscribir = New System.IO.StreamWriter(NombreFicheroAEscribir, False, System.Text.Encoding.Default)
'Escribir la linea con los nombres de las columnas : NO es obligatorio, pero en XLS, este da las cabetas de las columnas
LineaTMP = ""
For C As Integer = 0 To Ob_DataSetRegTO.Tables("TotalReg").Columns.Count - 1
LineaTMP &= Ob_DataSetRegTO.Tables("TotalReg").Columns(C).ColumnName & IIf(C < Ob_DataSetRegTO.Tables("TotalReg").Columns.Count - 1, SeparadorSplit, "")
Next
FicheroAEscribir.WriteLine(LineaTMP)
'Escribir las lineas con los datos (las lineas, una por una)
For R As Integer = 0 To Ob_DataSetRegTO.Tables("TotalReg").Rows.Count - 1
LineaTMP = ""
For C As Integer = 0 To Ob_DataSetRegTO.Tables("TotalReg").Columns.Count - 1
LineaTMP &= Ob_DataSetRegTO.Tables("TotalReg").Rows(R).Item(C) & IIf(C < Ob_DataSetRegTO.Tables("TotalReg").Columns.Count - 1, SeparadorSplit, "")
Next
FicheroAEscribir.WriteLine(LineaTMP)
Next
FicheroAEscribir.Close()
FicheroAEscribir.Dispose()
' Quiza el codigo siguiente es necesario
OB_AdapterRegTO.Dispose()
End Sub