我試圖創建一些數據的csv文件。我已經寫了一個函數,成功地做到這一點....在Streamwriter對象中使用本地文件路徑ASP.Net
Private Sub CreateCSVFile(ByVal dt As DataTable, ByVal strFilePath As String)
Dim sw As New StreamWriter(strFilePath, False)
''# First we will write the headers.
''#DataTable dt = m_dsProducts.Tables[0];
Dim iColCount As Integer = dt.Columns.Count
For i As Integer = 0 To iColCount - 1
sw.Write(dt.Columns(i))
If i < iColCount - 1 Then
sw.Write(",")
End If
Next
sw.Write(sw.NewLine)
''# Now write all the rows.
For Each dr As DataRow In dt.Rows
For i As Integer = 0 To iColCount - 1
If Not Convert.IsDBNull(dr(i)) Then
sw.Write(dr(i).ToString())
End If
If i < iColCount - 1 Then
sw.Write(",")
End If
Next
sw.Write(sw.NewLine)
Next
sw.Close()
End Sub
問題是我沒有正確使用我想要完成的Streamwriter對象。由於這是一個asp.net,我需要用戶選擇一個本地文件路徑來放置文件。如果我傳遞了這個函數的任何路徑,它會嘗試將它寫入代碼所在的服務器上指定的目錄。我想這個彈出並讓用戶選擇他們的本地機器上的一個地方放文件....
Dim exData As Byte() = File.ReadAllBytes(Server.MapPath(eio))
File.Delete(Server.MapPath(eio))
Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", fn))
Response.ContentType = "application/x-msexcel"
Response.BinaryWrite(exData)
Response.Flush()
Response.End()
我打電話這樣的代碼的第一個函數...
Dim emplTable As DataTable = SiteAccess.DownloadEmployee_H()
CreateCSVFile(emplTable, "C:\\EmplTable.csv")
我不想指定文件位置(因爲這會將文件放在服務器上而不是客戶機上),而是讓用戶在其客戶機上選擇位置。
有人可以幫我把它放在一起嗎?提前致謝。
我已經重新創建了我的導出函數,現在它讓usr選擇一個下載路徑,但是下載的數據中的一列有「Doe,John」形式的數據,這一列被稱爲「EPLNME」輸出文件,因爲它讀取數據中的逗號,現在數據已關閉輸出文件中的一列可以有人幫我阻止這個特定的事件我不知道我怎麼能。這裏是代碼...
Private Sub ExportCSV(ByVal data As DataTable, ByVal nameOfFile As String)
Dim context As HttpContext = HttpContext.Current
context.Response.Clear()
context.Response.ContentType = "text/csv"
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + nameOfFile + ".csv")
''#Write column header names
For i = 0 To data.Columns.Count - 1
If (i > 0) Then
context.Response.Write(",")
End If
context.Response.Write(data.Columns(i).ColumnName)
Next
context.Response.Write(Environment.NewLine)
''#Write data
For Each row As DataRow In data.Rows
For i = 0 To data.Columns.Count - 1
If (i > 0) Then
context.Response.Write(",")
End If
context.Response.Write(row.Item(i).ToString())
Next
context.Response.Write(Environment.NewLine)
Next
context.Response.End()
End Sub
我想對您的問題進行排序的格式這是非常難以理解的。 – Yoda 2010-05-11 16:10:34