从XML文件创建CSV文件



这段代码确实会创建一个Excel.csv文件,但它不是一个真正的csv。其中包含的只是VB从dgvStats.Rows.ToString创建的一些官样文章。我猜这里需要某种For...Each,但我不知道该怎么解决。

谢谢你的帮助!

Private Sub btnCreate_Click(sender As Object, e As EventArgs) Handles btnCreate.Click
    Dim StatsData As XElement = XElement.Load("Basketball.xml")
    Dim query = From p In StatsData.Descendants("player")
    Let name = p.<name>.Value
    Let team = p.<team>.Value
    Let points = CInt(p.<points>.Value)
    Let steals = CInt(p.<steals>.Value)
    Order By points Descending
    Select name, team, points, steals
    Dim sw As IO.StreamWriter = IO.File.CreateText("Basketball.csv")
    sw.WriteLine(dgvStats.Rows.ToString)
    sw.Close()
    MessageBox.Show("Basketball.csv created in binDebug folder. " &
                    "Use Windows Explorer to find it.")
End Sub

你想要这样的东西吗?

For Each x In query
    sw.WriteLine(String.Format("""{0}"", ""{1}"", {2}, {3}", x.name, x.team, x.points, x.stats)
Next

我还发现这段代码是有效的。

附言:SO代码格式在这里似乎无法正常工作。我输入的代码错了吗?

Private Sub btnCreate_Click(sender As Object, e As EventArgs) Handles btnCreate.Click
    'Create a new query which puts the XML data in CSV format. 
    'The last Let statement makes the change. This String is then Selected.
    Dim StatsData As XElement = XElement.Load("Basketball.xml")
    Dim queryCreate = From p In StatsData.Descendants("player")
    Let name = p.<name>.Value
    Let team = p.<team>.Value
    Let points = CInt(p.<points>.Value)
    Let steals = CInt(p.<steals>.Value)
    Let outputLine = CStr(name & "," & team & "," & points & "," & steals)
    Order By points Descending
    Select outputLine
    'Make sure that .txt file does not already exist, or else delete it
    'See CheckForExistingFile Sub definition below.
    CheckForExistingFile("Basketball.txt")
    'Write CSV file
    IO.File.WriteAllLines("Basketball.txt", queryCreate)
    MessageBox.Show("Basketball.txt CSV file has been created in binDebug. " &
                    "Close the program and hit Refresh in Solution Explorer " &
                    "to see it. Make sure that Show All Files is selected.")
End Sub
Private Sub CheckForExistingFile(file As String)
    'Check whether file has been created previously. If so, delete it.
    If IO.File.Exists(file) Then
        IO.File.Delete(file)
    End If
End Sub

最新更新