链接/ Web CSV到datagridview

时间:2014-06-06 11:55:57

标签: vb.net csv datagridview

我知道如何从本地CSV填充datagridview,但如何从包含CSV的链接填充Datagridview(例如http://financials.morningstar.com/ajax/ReportProcess4CSV.html?&t=XNAS:AAPL&region=usa&culture=en-US&cur=USD&reportType=is&period=12&dataType=A&order=desc&columnYear=5&rounding=3&view=raw&r=706201&denominatorView=raw&number=3

我有本地CSV的代码,第一行应该更改为指向链接,但我不知道如何。

 Dim TextFieldParser1 As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\finviz.csv")

        TextFieldParser1.Delimiters = New String() {","}

        While Not TextFieldParser1.EndOfData
            Dim Row1 As String() = TextFieldParser1.ReadFields()

            If DataGridView1.Columns.Count = 0 AndAlso Row1.Count > 0 Then
                Dim i As Integer

                For i = 0 To Row1.Count - 1
                    DataGridView1.Columns.Add("Column" & i + 1, "Column" & i + 1)
                Next
            End If

            DataGridView1.Rows.Add(Row1)
        End While

感谢。

2 个答案:

答案 0 :(得分:1)

试试:

    Dim myUri As New Uri("http://financials.morningstar.com/ajax/ReportProcess4CSV.html?&t=XNAS:AAPL&region=usa&culture=en-US&cur=USD&reportType=is&period=12&dataType=A&order=desc&columnYear=5&rounding=3&view=raw&r=706201&denominatorView=raw&number=3")
    Dim request As HttpWebRequest = DirectCast(WebRequest.Create(myUri), HttpWebRequest)
    Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
    Dim receiveStream As Stream = response.GetResponseStream()

    Dim TextFieldParser1 As New Microsoft.VisualBasic.FileIO.TextFieldParser(receiveStream)
    TextFieldParser1.Delimiters = New String() {","}
    While Not TextFieldParser1.EndOfData
        Dim Row1 As String() = TextFieldParser1.ReadFields()

        If DataGridView1.Columns.Count = 0 AndAlso Row1.Count > 0 Then
            Dim i As Integer

            For i = 0 To Row1.Count - 1
                DataGridView1.Columns.Add("Column" & i + 1, "Column" & i + 1)
            Next
        End If

        DataGridView1.Rows.Add(Row1)
    End While

    receiveStream.Close()
    response.Close()

答案 1 :(得分:0)

您需要在此行之前添加csv文本下载代码:

Dim TextFieldParser1 As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\finviz.csv")

在单独的线程上使用WebClient的{​​{3}}或DownloadFile(使用自己的独立线程)或DownloadFileAsyncHttpWebRequest类下载csv在使用TextFieldParser解析之前。

另外,请勿对文件名进行硬编码。