Joe Horn 的啟示錄

[VB.Net] 將 DataSet 匯出成 CSV 檔

剛剛弄出來的東西.

DsExport.vb :

Public Class DsExport

  Public Shared Function Export(ByVal ds As DataSet, _
                                ByVal dtName As String, _
                                ByVal colList() As String, _
                                ByVal colValue() As Integer) As String
    Dim header As String = ""
    Dim body As String = ""
    Dim record As String = ""

    For Each col As String In colList
      header = header & Chr(34) & col & Chr(34) & ","
    Next
      header = header.Substring(0, header.Length - 1)

    For Each row As DataRow In ds.Tables(dtName).Rows
      Dim arr() As Object = row.ItemArray()

      For Each i As Integer In colValue
        If arr(i).ToString().IndexOf(",") > 0 Then
          record = record & Chr(34) & arr(i).ToString() & Chr(34) & ","
        Else
          record = record & arr(i).ToString() & ","
        End If
      Next

      body = body & record.Substring(0, record.Length - 1) & vbCrLf
      record = ""
    Next

    Return header & vbCrLf & body

  End Function

End Class

呼叫方式:

  Private Sub BtnExport_Click(ByVal sender As System.Object, _
                              ByVal e As System.EventArgs) Handles BtnExport.Click
    Dim colList() As String = {"CSV表頭1", "CSV表頭2", "CSV表頭3"}

    "顯示順序: SQL query 刮出來的欄位0, 4, 2
    Dim colValue() As Integer = {0, 4, 2}

    Dim strData As String = _
      DsExport.Export(DataSet 變數名稱, _
                      "DataSet 變數中的 DataTabel 名稱", _
                      colList, colValue)

    Dim binData() As Byte = System.Text.Encoding.Default.GetBytes(strData)

    Response.Clear()
    Response.AddHeader("Content-Type", "application/vnd.ms-access")
    Response.AddHeader("Content-Disposition", "inline;filename=檔案名稱.csv")
    Response.BinaryWrite(binData)
    Response.End()
  End Sub
Exit mobile version