'filename ej informe1.csv
'sepChar ej | o , o ; Sub DataTable2CSV(ByVal table As DataTable, ByVal filename As String, _ByVal sepChar As String)
Dim writer As System.IO.StreamWriter
Try
writer = New System.IO.StreamWriter(filename)
Dim xx As String = DT2CSV(table, sepChar)
writer.Write(xx)
Finally
If Not writer Is Nothing Then writer.Close()
End Try
End Sub
'En esta funcion formateamos los datos para que el aneviarlos al csv cada columna del datatable quede en una columna del archivoPublic Function DT2CSV(ByVal DT As DataTable, Optional ByVal Separator As String = Nothing) As String
If DT Is Nothing Then Return String.Empty
If DT.Rows.Count = 0 Then Return String.Empty
Dim Result As String = String.Empty
'Inicializamos los encabezados
For I As Integer = 0 To DT.Columns.Count - 1
Result = Result &
"""" & DT.Columns(I).ColumnName & """" & Separator
Next
Result = Result.Substring(0, Result.Length - 1) & vbCrLfDim Line As String = String.Empty
For I As Integer = 0 To DT.Rows.Count - 1
For H As Integer = 0 To DT.Columns.Count - 1
If Not IsDBNull(DT.Rows(I)(H)) Then
Line = Line & """" & Quitar(CStr(DT.Rows(I)(H))) & """" & SeparatorElse
Line = Line & """" & String.Empty & """" & Separator
End If
Next
Line = Line.Substring(0, Line.Length - 1)
Result = Result & Line & vbCrLf
Line = String.EmptyNext
Return Result
End Function
'Con esta función eliminamos los espacios como enter tabs entre otros que pueden dañar el formatoPublic Function Quitar(ByVal Value As String, Optional ByVal Separador As String = Nothing) As String
Value = Value.Replace(vbCr, "")
Value = Value.Replace(vbCrLf, "")Value = Value.Replace(vbLf, "")
Value = Value.Replace(vbTab, "")
Value = Value.Replace(vbNewLine, "")
Value = Value.Replace("\n", "")
Value = Value.Replace("\r", "")
Replace(Value, vbNewLine, "", , , vbTextCompare)
Value = Replace(Replace(Replace(Value, Chr(10), ""), Chr(13), ""), Chr(9), "")
If Not Separador Is Nothing Then
Value = Value.Replace(Separador, String.Empty)End If
Return Value
End Function
Sub DataTable2TXT(ByVal table As DataTable, ByVal filename As String, _ByVal sepChar As String)
Dim writer As System.IO.StreamWriter
Try
writer = New System.IO.StreamWriter(filename)' first write a line with the columns name
Dim sep As String = ""
Dim builder As New System.Text.StringBuilder
For Each col As DataColumn In table.Columns
builder.Append(sep).Append(Quitar(col.ColumnName.ToString))
sep = sepChar
Next
writer.WriteLine(builder.ToString())
' then write all the rows
For Each row As DataRow In table.Rows
sep = ""
builder =New System.Text.StringBuilder
For Each col As DataColumn In table.Columns
builder.Append(sep).Append(row(Quitar(col.ColumnName.ToString)))
sep = sepCharNext
writer.WriteLine(builder.ToString())Next
Finally
If Not writer Is Nothing Then writer.Close()
End Try
End Sub
No hay comentarios.:
Publicar un comentario