daveofgv
Well-known member
Hello All -
I am trying to export a datagridview to excel.
Right now, I am using:
However, it is saying:
at line 575, which is:
Can anyone help with solving this?
thanks
I am trying to export a datagridview to excel.
Right now, I am using:
VB.NET:
Imports Excel = Microsoft.Office.Interop.Excel
Imports System.Data.OleDb
Imports System.IO.File
Imports System.IO
Imports System.Text
Private Sub ExporterDtgView()
SaveFileDialog2.Filter = "xls files (*.xls)|*.xls"
SaveFileDialog2.FilterIndex = 2
SaveFileDialog2.RestoreDirectory = True
Try
'chose the distination file
If SaveFileDialog2.ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
'It validates the edition of the DataGridView
DataGridView1.EndEdit()
'We are preparing a brief to write formatted data to the file
Dim ToSave As New StringBuilder()
'We'll put the headers as required :-)
Dim Headers As String = String.Empty
For index As Integer = 0 To DataGridView1.Columns.Count - 1
Headers &= DataGridView1.Columns(index).HeaderText & ";"
Next
'The loop adds a ";" at the end if it's useless
Headers = Headers.Remove(Headers.LastIndexOf(";"), 1)
'Now it is stored in the memory
ToSave.AppendLine(Headers)
'Loop over all available lines
For i As UInt64 = 0 To DataGridView1.Rows.Count - 1
'It is a variable to store a line
Dim OneRow As String = String.Empty
'You can do a loop on all the columns available if the line is not empty
If DataGridView1.Rows(i).IsNewRow = False Then
For j As Integer = 0 To DataGridView1.Rows(i).Cells.Count - 1
OneRow &= DataGridView1.Rows(i).Cells(j).Value & ";"
Next
OneRow = OneRow.Remove(OneRow.LastIndexOf(";"), 1)
ToSave.AppendLine(OneRow)
End If
Next
'now trying to write the file
IO.File.WriteAllText(SaveFileDialog1.FileName, ToSave.ToString(), Encoding.Default)
End If
Catch ex As Exception
MessageBox.Show(String.Format("{0}{1}{1}{2}", ex.Message, Environment.NewLine, ex.StackTrace))
End Try
End Sub
However, it is saying:
Empty Path Name Is Not Legal
at line 575, which is:
VB.NET:
IO.File.WriteAllText(SaveFileDialog1.FileName, ToSave.ToString(), Encoding.Default)
Can anyone help with solving this?
thanks