2013-05-08 74 views
0

我試圖將我的dgv的內容導出爲ex​​cel,但我遇到了一些錯誤。 我的代碼是:嘗試將datagridview的內容導出爲ex​​cel時出錯

Public Class Form1 
Dim dbProvider As String = "PROVIDER=microsoft.ace.oledb.12.0;" 
Dim dbSource As String = "Data Source = C:\D&R\Data\DR.accdb" 
Dim conn As New OleDb.OleDbConnection 
Dim ds As New DataSet 
Dim da As New OleDb.OleDbDataAdapter 
Dim sql As String 
Dim query As String = "SELECT AcctNum,SDI,Medicare,State,Fed,TotWages FROM Earnings INNER JOIN Personel On Earnings.SS=Personel.SS" 
Dim command As New OleDb.OleDbCommand(query, conn) 

Private Sub connect() 
    conn.ConnectionString = dbProvider & dbSource 
    conn.Open() 
    MsgBox(conn.State.ToString) 
End Sub 

Private Sub dgPopulate() 
    connect() 
    da.SelectCommand = command 
    da.Fill(ds) 
    Dim dt As New DataTable 
    da.Fill(dt) 

    Me.dgEmployees.DataSource = dt 
    conn.Close() 
End Sub 

Private Sub export() 
    Dim dgCount As Integer 
    dgCount = dgEmployees.Rows.Count 
    Dim output As New List(Of String) 
    For Each intAccNum As DataGridViewRow In dgEmployees.Rows 

     Dim empNumber As String = intAccNum.Cells(0).ToString 
     For i = 1 To 5 
      output.Add(empNumber + "," + CStr(intAccNum.Cells(i).Value + vbCrLf)) 
     Next 
    Next 
    System.IO.File.WriteAllLines("C:\users\fantus\documents\test.txt", output.ToArray) 
End Sub 

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load 
    dgPopulate() 
End Sub 

Private Sub ExportToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles ExportToolStripMenuItem.Click 
    export() 
End Sub 

End Class 

,我發現了錯誤:

"Conversion from string "" to type 'Double' is not valid." 

上:

output.Add(empNumber + "," + CStr(intAccNum.Cells(i).Value + vbCrLf)) 

回答

0

您要添加到vbCrLf.value。只將.value轉換爲一個字符串,然後添加回車符。