Crash Override
January 31st, 2008, 03:52 PM
Hi.
I have a application that fills a DATAGRIDVIEW, but i need to export that info to a new instance of EXCEL.
But I need to do it throu a command button.
Could anyone please tell me how to do it.
THANKS !!!
PeejAvery
February 1st, 2008, 09:06 AM
I just did this rather recently. Just remember to pass the DataGridView to the parameters.
Private Declare Function ShellEx Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hWnd As Integer, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Integer) As Integer
Private Sub exportExcel(ByVal grdView As DataGridView)
Dim myFile As String = My.Application.Info.DirectoryPath & "\" & "ExportedData.xls"
Dim fs As New IO.StreamWriter(myFile, False)
fs.WriteLine("<?xml version=""1.0""?>")
fs.WriteLine("<?mso-application progid=""Excel.Sheet""?>")
fs.WriteLine("<ss:Workbook xmlns:ss=""urn:schemas-microsoft-com:office:spreadsheet"">")
fs.WriteLine(" <ss:Styles>")
fs.WriteLine(" <ss:Style ss:ID=""1"">")
fs.WriteLine(" <ss:Font ss:Size=""14"" ss:Bold=""1""/>")
fs.WriteLine(" <ss:Alignment ss:Vertical=""Center""/>")
fs.WriteLine(" </ss:Style>")
fs.WriteLine(" <ss:Style ss:ID=""2"">")
fs.WriteLine(" <ss:Font ss:Bold=""1""/>")
fs.WriteLine(" <ss:Alignment ss:Horizontal=""Center"" ss:Vertical=""Center"" ss:WrapText=""1""/>")
fs.WriteLine(" <ss:Interior ss:Color=""#C0C0C0"" ss:Pattern=""Solid""/>")
fs.WriteLine(" </ss:Style>")
fs.WriteLine(" <ss:Style ss:ID=""3"">")
fs.WriteLine(" <ss:Alignment ss:Vertical=""Center"" ss:WrapText=""1""/>")
fs.WriteLine(" </ss:Style>")
fs.WriteLine(" </ss:Styles>")
fs.WriteLine("<ss:Worksheet ss:Name=""Sheet1"">")
fs.WriteLine(" <ss:Table>")
For i As Integer = 0 To grdView.Columns.Count - 1
fs.WriteLine(String.Format(" <ss:Column ss:Width=""{0}""/>", grdView.Columns.Item(i).Width))
Next
fs.WriteLine(" <ss:Row>")
For i As Integer = 0 To grdView.Columns.Count - 1
fs.WriteLine(String.Format(" <ss:Cell ss:StyleID=""2""><ss:Data ss:Type=""String"">{0}</ss:Data></ss:Cell>", grdView.Columns.Item(i).HeaderText))
Next
fs.WriteLine(" </ss:Row>")
For i As Integer = 0 To grdView.RowCount - 1
fs.WriteLine(String.Format(" <ss:Row ss:Height=""{0}"">", grdView.Rows(i).Height))
For intCol As Integer = 0 To grdView.Columns.Count - 1
fs.WriteLine(String.Format(" <ss:Cell ss:StyleID=""3""><ss:Data ss:Type=""String"">{0}</ss:Data></ss:Cell>", grdView.Item(intCol, i).Value.ToString))
Next
fs.WriteLine(" </ss:Row>")
Next
fs.WriteLine(" </ss:Table>")
fs.WriteLine("</ss:Worksheet>")
fs.WriteLine("</ss:Workbook>")
fs.Close()
ShellEx(Me.Handle, "open", myFile, "", "", 10)
End Sub