Hi, here i am again
here you have the code to export grid to excel or word
Exp = "Word" Then 'export to word
Exp = "Excel" Then 'export to excel
template= preconfigured template file in excel or word
rgrds,
Public Function ExportDataGridView(ByRef dgv As DataGridView, ByVal Fname As String, ByVal Exp As String, ByVal Template As String) As String
Try
Dim s As String = ""
Dim oCurrentCol As DataGridViewColumn
oCurrentCol = dgv.Columns.GetFirstColumn(DataGridViewElementStates.Visible)
Do
s &= oCurrentCol.HeaderText & Chr(Keys.Tab)
oCurrentCol = dgv.Columns.GetNextColumn(oCurrentCol, DataGridViewElementStates.Visible, DataGridViewElementStates.None)
Loop Until oCurrentCol Is Nothing
s = s.Substring(0, s.Length - 1)
s &= Environment.NewLine
For Each row As DataGridViewRow In dgv.Rows
oCurrentCol = dgv.Columns.GetFirstColumn(DataGridViewElementStates.Visible)
Do
If row.Cells(oCurrentCol.Index).Value IsNot Nothing Then
s &= Replace(row.Cells(oCurrentCol.Index).Value.ToString, Chr(10), " - ")
Else
s &= " "
End If
s &= Chr(Keys.Tab)
oCurrentCol = dgv.Columns.GetNextColumn(oCurrentCol, DataGridViewElementStates.Visible, DataGridViewElementStates.None)
Loop Until oCurrentCol Is Nothing
s = s.Substring(0, s.Length - 1)
s &= Chr(13)
Next
Dim o As New DataObject
o.SetText(s)
Clipboard.SetDataObject(o, True)
Catch ex As Exception
Return "0"
End Try
If Exp = "Excel" Then
Dim oldCI As System.Globalization.CultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture
Dim oExcel As Excel.ApplicationClass
oExcel = New Excel.ApplicationClass
Dim oBook As Object
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US")
Try
oBook = oExcel.Workbooks.Open(Template)
oBook.Worksheets(1).Range("A1").Select()
oBook.Worksheets(1).Paste()
oBook.SaveAs(Frm1.LblTemp.Text & "Temp\" & Fname & Format(Now, "yyMMddHHmm") & ".xls")
oBook = Nothing
CheckExcel(False)
oExcel = Nothing
GC.Collect()
System.Threading.Thread.CurrentThread.CurrentCulture = oldCI
Return Frm1.LblTemp.Text & "Temp\" & Fname & Format(Now, "yyMMddHHmm") & ".xls"
Catch ex As Exception
oBook = Nothing
CheckExcel(False)
oExcel = Nothing
System.Threading.Thread.CurrentThread.CurrentCulture = oldCI
Return "0"
End Try
ElseIf Exp = "Word" Then
Dim oWord As Microsoft.Office.Interop.Word.ApplicationClass
oWord = New Microsoft.Office.Interop.Word.ApplicationClass
Dim oDoc As Microsoft.Office.Interop.Word.Document
Try
oDoc = oWord.Documents.Open(Template)
Dim WordRange = oWord.ActiveDocument.Range(Start:=0, End:=0)
WordRange.Paste()
oDoc.SaveAs(Frm1.LblTemp.Text & "Temp\" & Fname & Format(Now, "yyMMddHHmm") & ".doc")
oDoc = Nothing
oWord.Quit()
oWord = Nothing
Return Frm1.LblTemp.Text & "Temp\" & Fname & Format(Now, "yyMMddHHmm") & ".doc"
Catch ex As Exception
oDoc = Nothing
oWord.Quit()
oWord = Nothing
Return "0"
End Try
Else
Return "0"
End If
End Function