这可以正常工作,假设某些单元格中没有换行符。
dgvResults.SelectAllCells()
dgvResults.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader
ApplicationCommands.Copy.Execute(Nothing, dgvResults)
Dim result As [String] = DirectCast(Clipboard.GetData(DataFormats.CommaSeparatedValue), String)
Clipboard.Clear()
dgvResults.UnselectAllCells()
Try
Dim file As New System.IO.StreamWriter("c:\export.csv")
file.WriteLine(result)
file.Close()
Process.Start("c:\export.csv")
Catch ex As Exception
MessageBox.Show(ex.Message, "Error")
End Try
这是我添加换行符的方式
Dim x As New List(Of String)
For Each item In res.Properties("proxyaddresses")
x.Add(item)
Next
AllSMTPAddresses = String.Join(ControlChars.Lf, x)
当我导出它时,它没有考虑到有换行符,并且完全忽略它们......所以excel格式有点不稳定。我尝试过:Environment.NewLine,vbCrLf,现在是ControlChars.Lf。我认为excel不知道如何处理换行符,所以它只是想要它,并用它们创建新的行。
关于我如何攻击这个的任何想法?
更新结果@Jimmy
这应该是它的样子......
答案 0 :(得分:1)
我不相信这可以在导出之前修改这些行。我发现了一些可能有用的示例代码,
Public Sub writeCSV(grid1 As Object, outputFile As String)
' Create the CSV file to which grid data will be exported.
Dim sw As New StreamWriter(outputFile)
' First we will write the headers.
Dim dt As DataTable = DirectCast(grid1.DataSource, DataSet).Tables(0)
Dim iColCount As Integer = dt.Columns.Count
For i As Integer = 0 To iColCount - 1
sw.Write(dt.Columns(i))
If i < iColCount - 1 Then
sw.Write(",")
End If
Next
sw.Write(sw.NewLine)
' Now write all the rows.
For Each dr As DataRow In dt.Rows
For i As Integer = 0 To iColCount - 1
sw.Write("""") 'lets encapsulate those fields in quotes, quoted csv file!
If Not Convert.IsDBNull(dr(i)) Then
sw.Write(dr(i).ToString())
End If
sw.Write("""")
If i < iColCount - 1 Then
sw.Write(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator)
End If
Next
sw.Write(sw.NewLine)
Next
sw.Close()
End Sub