【问题标题】:Create a CSV file from an XML file?从 XML 文件创建 CSV 文件?
【发布时间】:2014-11-12 09:50:44
【问题描述】:

此代码确实会创建一个 Excel .csv 文件,但它不是真正的 CSV。它将包含在其中的所有内容都是 VB 从dgvStats.Rows.ToString 创建的一些 gobbledygook。我猜这里需要某种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 bin\Debug folder. " &
                    "Use Windows Explorer to find it.")
End Sub

【问题讨论】:

    标签: xml vb.net csv


    【解决方案1】:

    你追求的是这样的东西吗?

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

    【讨论】:

    • 非常,是的。让我试试看。
    • 酷!是的,这很好用,尽管它在字符串对象周围留下了引号格式,这使得 .txt 文件更难使用。有没有其他的格式化方式?
    • " 放在字符串周围涵盖了, 出现在字符串中的情况。你能告诉我为什么它使文本文件更难使用吗?
    【解决方案2】:

    我还发现这段代码有效。

    附: 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 bin\Debug. " &
                        "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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-15
      • 1970-01-01
      • 2014-05-29
      • 2016-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多