除了从视图中导出必填字段外,我还需要导出一个附加字段,密码。视图中不存在此字段。这是加密studentId字段的结果。例如,如果StudentId为'1234567',则其密码为' ABCDEFG'。我的代码如下。
'assume the connection works
cmd1.CommandText = "select studentID from vwTEST"
cmd1.ExecuteNonQuery()
da.Fill(dt)
For i As Integer = 0 To dt.Rows.Count - 1
strStudentID = dt.Rows(i).Item(0)
enc = encrypt(strStudentID) ‘assume this function works
updatePW(strStudentID, enc)
Next
一切正常。但规则是我不能将密码放入学生表中。另外,我不能在SQL Server上使用UDF。因此,我尝试创建一个美化表,我将所有数据放在那里,然后我会尝试在将数据导出到csv文件之前将密码(由加密函数创建)放在该虚拟表中。我怎样才能做到这一点?你能帮忙吗?提前谢谢。
答案 0 :(得分:2)
虽然评论中提到的原始帖子应该有足够的帮助,但这段代码也应该起作用
ExportToCSV函数将DataTable和FileName作为参数,成功时返回True,失败时返回False(并将错误打印到控制台)
你可以在我放置备注的地方进行用户名加密,或者在导出之前将它们添加到数据表中
导出的csv文件适用于MS Excel& SpreadSheets(KingSoft办公室)
Imports System.IO
Imports System.Text
Module Module1
Function wrapValue(value As String, group As String, separator As String) As String
If value.Contains(separator) Then
If value.Contains(group) Then
value = value.Replace(group, group + group)
End If
value = group & value & group
End If
Return value
End Function
Function ExportToCSV(dtable As DataTable, fileName As String) As Boolean
Dim result As Boolean = True
Try
Dim sb As New StringBuilder()
Dim separator As String = ";"
Dim group As String = """"
Dim newLine As String = Environment.NewLine
For Each column As DataColumn In dtable.Columns
sb.Append(wrapValue(column.ColumnName, group, separator) & separator)
Next
' here you could add the column for the username
sb.Append(newLine)
For Each row As DataRow In dtable.Rows
For Each col As DataColumn In dtable.Columns
sb.Append(wrapValue(row(col).ToString(), group, separator) & separator)
Next
' here you could extract the password for the username
sb.Append(newLine)
Next
Using fs As New StreamWriter(fileName)
fs.Write(sb.ToString())
End Using
Catch ex As Exception
Console.WriteLine(ex.Message & vbCrLf & ex.StackTrace)
result = False
End Try
Return result
End Function
Sub Main()
Dim dt As New DataTable
dt.Columns.Add("String Column", GetType(String))
dt.Columns.Add("Integer Column", GetType(Integer))
dt.Columns.Add("Bool Column", GetType(Boolean))
dt.Columns.Add("Double Column", GetType(Double))
For i As Integer = 0 To 10
dt.Rows.Add("string "";value " & i, i, IIf(i Mod 2, True, False), Math.Sqrt(i))
Next
If ExportToCSV(dt, Path.Combine(Environment.CurrentDirectory, "TestFile.csv")) Then
Console.WriteLine("CSV File succesfully written")
End If
Console.ReadLine()
End Sub
End Module