此代码确实会创建一个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
答案 0 :(得分:0)
这样的事情是你之后的事吗?
For Each x In query
sw.WriteLine(String.Format("""{0}"", ""{1}"", {2}, {3}", x.name, x.team, x.points, x.stats)
Next
答案 1 :(得分:0)
我还发现此代码有效。
P.S。这里的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