我有一个应用程序UWP,可将数据从CSV文件导入到ListView。
如何将数据放入DataGrid?现在,我使用以下代码将数据放入ListView:
Dim CsvRows = New ObservableCollection(Of String)()
Dim picker = New Windows.Storage.Pickers.FileOpenPicker()
picker.ViewMode = PickerViewMode.List
picker.FileTypeFilter.Add(".csv")
Dim file = Await picker.PickSingleFileAsync()
CsvRows.Clear()
Using csvReader = New CsvParse.CsvFileReader(Await file.OpenStreamForReadAsync())
Dim row = New CsvParse.CsvRow()
While csvReader.ReadRow(row)
Dim newRow = ""
For i = 0 To row.Count
newRow += row(i) + ","
i += 1
Next
CsvRows.Add(newRow)
End While
End Using
GridTabacchi.ItemsSource = CsvRows
答案 0 :(得分:0)
将数据从CSV文件导入到datagrid
通常,我们经常使用CsvReader
隐蔽的csv文件来收集可以直接绑定到DataGrid
列的文件。这是您可以参考的官方document。我将在下面提供示例代码。
模型类
Public Class Item
Public Property Id As String
Public Property Title As String
Public Property Link As String
Public Property Type As String
Public Property Remark As String
Public Property Time As String
End Class
背后的代码
Private Sub DataGrid_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs)
Using reader = New StreamReader("Assets\Archive.csv", True)
Using csv = New CsvReader(reader)
Dim records = csv.GetRecords(Of Item)()
For Each item In records
Items.Add(item)
Next
End Using
End Using
MyDataGrid.ItemsSource = Items
End Sub
使DataGridTextColumn
基于模型类,并按如下所示绑定每个属性。
<controls:DataGrid.Columns>
<controls:DataGridTextColumn
Width="*"
Binding="{Binding Id}"
Header="ID"
Tag="Id"
/>
<controls:DataGridTextColumn
Width="*"
Binding="{Binding Title}"
Header="Title"
Tag="Title"
/>
<controls:DataGridComboBoxColumn
Width="*"
Binding="{Binding Link}"
Header="Link"
ItemsSource="{x:Bind source}"
Tag="Link"
/>
<controls:DataGridTextColumn
Width="*"
Binding="{Binding Type}"
Header="Type"
Tag="Type"
/>
<controls:DataGridTextColumn
Width="*"
Binding="{Binding Remark}"
Header="Remark"
Tag="Remark"
/>
<controls:DataGridTextColumn
Width="*"
Binding="{Binding Time}"
Header="Time"
Tag="Time"
/>
</controls:DataGrid.Columns>
答案 1 :(得分:0)
我在公司的VB .NET应用程序中创建了一个.CSV上传文件,并显示在网格中。这是我的方法:
Dim dt as DataTable = New DataTable
Dim firstLine As Boolean = True
Dim sr As StreamReader = New StreamReader(txtFileLocation.Text.Trim())
Do While sr.Peek() >= 0
If firstLine Then
firstLine = False
Dim cols() As String = sr.ReadLine.Split(","c)
For Each col As String In cols
dt.Columns.Add(New DataColumn(col, GetType(String)))
Next
Else
Dim data() As String = sr.ReadLine.Split(","c)
dt.Rows.Add(data)
End If
Loop
sr.Close()
dataGrid.DataSource = dt