出力イメージ
「CSV出力」ボタン押下時にCSVファイルを出力する
VB
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'1, 2列目のみ抽出(重複排除なし)
dt = dt.DefaultView.ToTable(False, "Col1", "Col2")
Dim sb As New StringBuilder
Using sr As New System.IO.StreamWriter("output.csv", False, Encoding.GetEncoding("utf-8"))
'ヘッダ編集
For Each col As DataColumn In dt.Columns
If sb.Length > 0 Then
sb.Append(",")
End If
sb.Append("""").Append(col.ColumnName).Append("""")
Next
'データ編集
For Each row As DataRow In dt.Rows
sb.AppendLine()
sb.Append(String.Join(",",
row.ItemArray.Select(
Function(data) """" & data & """")))
Next
'CSV出力
sr.Write(sb.ToString)
End Using
End Sub
動作確認用コード
VB
Dim dt As New DataTable
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
With dt
.Columns.Add("Col1")
.Columns.Add("Col2")
.Columns.Add("Col3")
.Rows.Add("A001", "B001", "C001")
.Rows.Add("A002", "B002", "C002")
.Rows.Add("A003", "B003", "C003")
.Rows.Add("A004", "B004", "C004")
.Rows.Add("A005", "B005", "C005")
End With
'DGV設定
With DataGridView1
.DataSource = dt
.AllowUserToAddRows = False
.ClearSelection()
End With
End Sub
コメント