3

下面的代码将我的 CSV 文件导入数据网格。唯一的问题是它使用 CSV 文件中的一行填充标题,我希望标题留空并在其后导入行。请指教。

        If OpenFileDialog1.ShowDialog(Me) = DialogResult.OK Then


        Dim fi As New FileInfo(OpenFileDialog1.FileName)
        Dim sConnectionStringz As String = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Text;Data Source=" & fi.DirectoryName
        Dim objConn As New OleDbConnection(sConnectionStringz)
        objConn.Open()
        'DataGridView1.TabIndex = 1
        Dim objCmdSelect As New OleDbCommand("SELECT * FROM " & fi.Name, objConn)
        Dim objAdapter1 As New OleDbDataAdapter
        objAdapter1.SelectCommand = objCmdSelect
        Dim objDataset1 As New DataSet
        objAdapter1.Fill(objDataset1, "test")
        '--objAdapter1.Update(objDataset1) '--updating
        DataGridView1.DataSource = objDataset1.Tables(0).DefaultView

        objConn.Close()
    End If
4

1 回答 1

0

想到了两个想法,当在grid_ColumnAdded 事件处理程序中添加列时,只需将标题单元格清空

  if e.Column.HeaderText = "YourColumnHeaderText" Then        
     e.Column.HeaderText = String.Empty;

或者使用流式阅读器读取 CSV 文件可能更容易,参考: http: //www.dotneter.com/import-csv-file-into-datagridview(注意我会加载到数据表中而不是直接填充网格) :

Dim streamReader As System.IO.StreamReader = New StreamReader(txtPath.Text)

'Reading CSV file header
rowValue = streamReader.ReadLine()
cellValue = rowValue.Split(","C)
Dim i As Integer = 0
While i <= cellValue.Count() - 1
    Dim column As New DataGridViewTextBoxColumn()
    column.Name = cellValue(i)
    column.HeaderText = cellValue(i)
    dataGridView1.Columns.Add(column)
    i += 1
End While

'Reading CSV file content
While streamReader.Peek() <> -1
    rowValue = streamReader.ReadLine()
    cellValue = rowValue.Split(","C)
    dataGridView1.Rows.Add(cellValue)
End While

最后一个想法是在分配给网格数据源之前从数据表中删除一行:http: //msdn.microsoft.com/en-us/library/feh3ed13 (v=vs.80).aspx

objDataset1.Tables(0).Rows[0].Delete();

于 2012-04-22T00:57:41.770 回答