如何在没有标题的情况下将datagridview导出到.csv?

时间:2017-11-07 17:52:19

标签: vb.net datagridview

我的csv文件就像this 没有空格或任何空格。

您可以看到的问题是我不知道如何将我的datagridview导出为.csv,不包括列标题。

这就是我完成导出代码的方式:

    Private Sub IncomeToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles IncomeToolStripMenuItem.Click
    Dim saveFileDialog1 As New SaveFileDialog()

    saveFileDialog1.Filter = "CSV|*.csv"
    saveFileDialog1.RestoreDirectory = True

    If saveFileDialog1.ShowDialog() = DialogResult.OK Then
        Dim incomefile As String = String.Empty

        For Each column As DataGridViewColumn In Expense.Columns
            incomefile = incomefile & column.HeaderText & ","
        Next

        incomefile = incomefile.TrimEnd(",")
        incomefile = incomefile & vbCr & vbLf

        For Each row As DataGridViewRow In Expense.Rows
            For Each cell As DataGridViewCell In row.Cells
                incomefile = incomefile & cell.FormattedValue.replace(",", "") & ","
            Next
            incomefile = incomefile.TrimEnd(",")
            incomefile = incomefile & vbCr & vbLf
        Next
        System.IO.File.WriteAllText(saveFileDialog1.FileName, incomefile)
    End If

    Dim msg1 = "Export Successful"
    Dim title = "Excel Export"
    MsgBox(msg1, , title)
End Sub

请告诉我。其他一些人提到我最好使用数据表导出它,但自从我43小时前开始学习计算机编程以来,我不知道如何声明我在datagridview中输入的数据并将其导出为csv文件。

2 个答案:

答案 0 :(得分:1)

删除这些行

For Each column As DataGridViewColumn In Expense.Columns
  incomefile = incomefile & column.HeaderText & ","
Next

答案 1 :(得分:0)

试一试。

Private Sub BtnExport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnExport.Click
        SFD.InitialDirectory = "C:\"
        SFD.Title = "Save Your File"
        SFD.Filter = "Microsoft Excel(*.xls)|*.xls|Comma Delimited File(*.csv)|*.Csv"
        SFD.OverwritePrompt = True
        SFD.ShowDialog()
        strFileName = SFD.FileName
        ' If SFD.ShowDialog() = DialogResult.OK Then
        If SFD.FilterIndex = 1 Then
            Call export()
        Else
            Call csv()
        End If
        ' End If

    End Sub

另外,请尝试这种方式。

Dim numCols As DataGridViewCell
        Dim sw As New System.IO.StreamWriter("d:\\output.txt")
        For Each numRows As DataGridViewRow In DataGridView1.Rows
            Dim intCellCount As Integer = numRows .Cells.Count
            Dim intCounter As Integer = 1
            For Each numCols  In numRows .Cells()
                If intCounter <> intCellCount Then
                    sw.Write(numCols .Value.ToString & ",")
                Else
                    sw.WriteLine(numCols .Value.ToString)
                End If
                intCounter += 1
            Next
        Next