Export DataGridView to Excel using VB 2013 - vb.net

Im fairly new to VB 2013. Any advice and help is greatly appreciated.
I have a datagridview that I want to export to Excel. I have the code working that does the export, but it doesnt show the header names. I need to edit the code to bring the header names over as well.
Additionally, I want to drop the first column from the export.
Example of my gridview code:
Private Sub Button2_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button2.Click
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Dim i As Integer
Dim j As Integer
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("Sheet1")
'Export Header Names Start
Dim columnsCount As Integer = DataGridView1.Columns.Count
For Each column In DataGridView1.Columns
xlWorkSheet.Cells(1, column.Index + 1).Value = column.name
Next
' 'Export Header Name End
For i = 0 To DataGridView1.RowCount - 2
For j = 0 To DataGridView1.ColumnCount - 1
xlWorkSheet.Cells(i + 1, j + 1) = _
DataGridView1(j, i).Value.ToString()
Next
Next
If System.IO.File.Exists("C:\test\export.xlsx") Then
System.IO.File.Delete("C:\test\export.xlsx")
End If
xlWorkSheet.SaveAs("C:\test\export.xlsx")
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
MsgBox("You can find the file here C:\test")
End Sub
DataGridview Output:

For many years i,m using this function.
Public Sub grid_ToExcel_Export(ByVal FileName As String, ByVal Data_GridView As DataGridView)
Dim sb As New System.Text.StringBuilder
Try
Dim intColumn, intColumnValue As Integer
Dim row As DataGridViewRow
For intColumn = 0 To Data_GridView.Columns.Count - 1
sb.Append(Data_GridView.Columns(intColumn).HeaderText)
If intColumnValue <> Data_GridView.Columns.Count - 1 Then
sb.Append(vbTab)
End If
Next
sb.Append(vbCrLf)
For Each row In Data_GridView.Rows
For intColumnValue = 0 To Data_GridView.Columns.Count - 1
sb.Append(StrConv(IIf(IsDBNull(row.Cells(intColumnValue).Value), "", row.Cells(intColumnValue).Value), VbStrConv.None))
If intColumnValue <> Data_GridView.Columns.Count - 1 Then
sb.Append(vbTab)
End If
Next
sb.Append(vbCrLf)
Next
SaveExcel(FileName, sb)
Catch ex As Exception
Throw
Finally
Data_GridView = Nothing
sb = Nothing
End Try
End Sub
Private Sub SaveExcel(ByVal fpath As String, ByVal sb As System.Text.StringBuilder)
Dim fsFile As New FileStream(fpath, FileMode.Create, FileAccess.Write)
Dim strWriter As New StreamWriter(fsFile, System.Text.Encoding.Unicode)
Try
With strWriter
.BaseStream.Seek(0, SeekOrigin.End)
.WriteLine(sb)
.Close()
End With
Catch e As Exception
msg(e.ToString)
Finally
sb = Nothing
strWriter = Nothing
fsFile = Nothing
End Try
End Sub

Related

Uploading file to datagridview

I have this program where I am trying to upload an excel file and will be shown in my datagridview but i having this error
Additional information: Could not find installable ISAM.
Im new to VB please help me
Here is my code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Con As System.Data.OleDb.OleDbConnection
Dim ds As System.Data.DataSet
Dim cmd As System.Data.OleDb.OleDbDataAdapter
Con = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source='c:\manpower.xlsx';Extended Properties=cc;")
cmd = New System.Data.OleDb.OleDbDataAdapter("select * from [Sheet2$]", Con)
ds = New System.Data.DataSet
cmd.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
Con.Close()
End Sub
Why are you using OLEDB connection in the first place? Why not sqlConnection?
If you can, use something like this:
Private Sub LoadFormData()
Dim cmdText as String
Dim ds as DataSet
cmdText = "SELECT ID, FName, SName, Title FROM PeopleTable;"
ds = GetQueryResults(cmdText)
Me.DataGridView1.DataSource = ds.Tables(0)
End Sub
Private Function GetQueryResults(cmdText As String)
Dim oConn As New SqlConnection
oConn.ConnectionString = "........." ' your connection string
Dim cmd As New SqlCommand(cmdText, oConn)
Dim ds As New DataSet()
Dim da As New SqlDataAdapter(cmd)
Try
oConn.Open()
da.Fill(ds)
oConn.Close()
Catch ex As Exception ' handle error any way you like
Dim errform As New SysErrScreen
errform.ErrText.Text = ex.Message & vbCrLf & vbCrLf & cmdText
errform.ShowDialog()
oConn.Close()
End Try
Return ds
End Function
You can easily import an Excel file into DataGridView, and export from DataGridView to Excel.
Imports Excel = Microsoft.Office.Interop.Excel
Imports System.Data.OleDb
'~~> Define your Excel Objects
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim xlApp As New Excel.Application
'Dim xlWorkBook As Excel.Workbook
'Dim xlWorkSheet As Excel.Worksheet
Dim strConn As String
Dim da As OleDbDataAdapter
Dim ds As New DataSet
Dim dao_dbE As dao.DBEngine
Dim dao_DB As DAO.Database
Dim strFirstSheetName As String
dao_dbE = New dao.DBEngine
dao_DB = dao_dbE.OpenDatabase("C:\your_path_here\Book1.xls", False, True, "Excel 8.0;")
strFirstSheetName = dao_DB.TableDefs(0).Name
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\your_path_here\Book1.xls;Extended Properties=""Excel 8.0;"""
da = New OleDbDataAdapter("SELECT * FROM [" & _
strFirstSheetName & "]", strConn)
da.TableMappings.Add("Table", "Excel")
da.Fill(ds)
DataGridView1.DataSource = ds.Tables(0).DefaultView
da.Dispose()
dao_DB.Close()
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Dim rowsTotal, colsTotal As Short
Dim I, j, iC As Short
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor
Dim xlApp As New Excel.Application
Try
Dim excelBook As Excel.Workbook = xlApp.Workbooks.Add
Dim excelWorksheet As Excel.Worksheet = CType(excelBook.Worksheets(1), Excel.Worksheet)
xlApp.Visible = True
rowsTotal = DataGridView1.RowCount - 1
colsTotal = DataGridView1.Columns.Count - 1
With excelWorksheet
.Cells.Select()
.Cells.Delete()
For iC = 0 To colsTotal
.Cells(1, iC + 1).Value = DataGridView1.Columns(iC).HeaderText
Next
For I = 0 To rowsTotal - 1
For j = 0 To colsTotal - 1
.Cells(I + 2, j + 1).value = DataGridView1.Rows(I).Cells(j).Value
Next j
Next I
.Rows("1:1").Font.FontStyle = "Bold"
.Rows("1:1").Font.Size = 10
.Cells.Columns.AutoFit()
.Cells.Select()
.Cells.EntireColumn.AutoFit()
.Cells(1, 1).Select()
End With
Catch ex As Exception
MsgBox("Export Excel Error " & ex.Message)
Finally
'RELEASE ALLOACTED RESOURCES
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default
xlApp = Nothing
End Try
End Sub
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Dim i As Integer
Dim j As Integer
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
For Each col As DataGridViewColumn In Me.DataGridView1.Columns
xlWorkSheet.Cells(1, col.Index + 1) = col.HeaderText.ToString
Next
Try
For CurrentRowIndex = 0 To DataGridView1.RowCount - 1 'current row index
'For j = 0 To Me.DataGridView1.ColumnCount
For CurrentColumnIndex = 0 To DataGridView1.ColumnCount - 1 'current column index within row index
xlWorkSheet.Cells(2, CurrentColumnIndex + 1) = DataGridView1.Columns(CurrentColumnIndex).HeaderText 'display header
xlWorkSheet.Cells(CurrentRowIndex + 3, CurrentColumnIndex + 1) = DataGridView1(CurrentColumnIndex, CurrentRowIndex).Value.ToString()
Next
'xlWorkSheet.Cells(2, CurrentColumnIndex + 1) = DataGridView1.Columns(CurrentColumnIndex).HeaderText 'display header
'xlWorkSheet.Cells(i + 2, j + 1) = Me.DataGridView1(j, i).Value.ToString()
'xlWorkSheet.Cells(2, CurrentColumnIndex + 1) = DataGridView1.Columns(CurrentColumnIndex).HeaderText 'display header
'Next
Next
Catch ex As Exception
MsgBox("Unable to extract data" & ex.Message, MsgBoxStyle.Critical)
Exit Sub
End Try
xlWorkBook.Activate()
'//get path
Me.FolderBrowserDialog1.ShowDialog()
Dim path As String = Me.FolderBrowserDialog1.SelectedPath
xlWorkBook.SaveAs(path & "\Excel_With_Headers.xls")
'xlWorkSheet.SaveAs("burn permit export.xls")
xlWorkBook.Close()
xlApp.Quit()
'releaseObject(xlApp)
'releaseObject(xlWorkBook)
'releaseObject(xlWorkSheet)
MsgBox("You can find your report at " & path & "\burn permit export.xls")
End Sub
Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Dim i As Integer
Dim j As Integer
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
Try
For CurrentRowIndex = 0 To DataGridView1.RowCount - 1 'current row index
'xlWorkSheet.Cells(1, 1) = "With Headers"
For CurrentColumnIndex = 0 To DataGridView1.ColumnCount - 1 'current column index within row index
xlWorkSheet.Cells(2, CurrentColumnIndex + 1) = DataGridView1.Columns(CurrentColumnIndex).HeaderText 'display header
xlWorkSheet.Cells(CurrentRowIndex + 3, CurrentColumnIndex + 1) = DataGridView1(CurrentColumnIndex, CurrentRowIndex).Value.ToString()
Next
Next
Catch ex As Exception
MsgBox("Unable to extract data" & ex.Message, MsgBoxStyle.Critical)
Exit Sub
End Try
End Sub
End Class

Does not export datagridview data to excel vb.net

Im exporting a datagridview to excel, when I export the rows that contains data only for one year it works very well, but when I do for 2 or more years It does not export, my winform collapse.In total, I have 135159 rows to export.
this is my code
Dim exApp As New Microsoft.Office.Interop.Excel.Application
Dim exLibro As Microsoft.Office.Interop.Excel.Workbook
Dim exHoja As Microsoft.Office.Interop.Excel.Worksheet
Try
exLibro = exApp.Workbooks.Add
exHoja = exLibro.Worksheets.Add()
Dim NCol As Integer = dgvDatos.ColumnCount
Dim NRow As Integer = dgvDatos.RowCount
'this is to export columns
For i As Integer = 1 To NCol
exHoja.Cells.Item(1, i) = dgvDatos.Columns(i - 1).Name.ToString
Next
'this is to export all the rows
For Fila As Integer = 0 To NRow - 1
For Col As Integer = 0 To NCol - 1
exHoja.Cells.Item(Fila + 2, Col + 1) = dgvDatos.Item(Col, Fila).Value
Next
Next
It would be great if you could help me, Thankss!!
Try this code:
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Dim xlApp As Microsoft.Office.Interop.Excel.Application
Dim xlWorkBook As Microsoft.Office.Interop.Excel.Workbook
Dim xlWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Dim i As Integer
Dim j As Integer
xlApp = New Microsoft.Office.Interop.Excel.Application
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
'FOR HEADERS
For i = 1 To DataGridView1.ColumnCount
xlWorkSheet.Cells(1, i) = DataGridView1.Columns(i - 1).HeaderText
'FOR ITEMS
For j = 1 To DataGridView1.RowCount
xlWorkSheet.Cells(j + 1, i) = DataGridView1(i - 1, j - 1).Value.ToString()
Next
Next
xlWorkSheet.SaveAs("D:\vbexcel.xlsx")
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
MsgBox("You can find the file D:\vbexcel.xlsx")
End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
End Class
The path is in the D: and the file name is vbexcel.xlsx
Note: choosing No will get an error cause it will replace the file with the same file name in the same path. Always choose Yes to replace the existing file.

export datagridview header column to excel vb 2012

i'm using visual studio 2012 and microsoft SQL server 2012 to export datagridview to excel using this coding:
Public Class Export
Private Sub Export_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DataGridView1.AllowUserToAddRows = False
ClassKoneksi.namadatabase = "KPIRWAN"
Dim dssiswa As New DataSet
Dim sql As String
sql = "select*from Siswa order by NIS ASC"
dssiswa = ClassSiswa.displayData(ClassSiswa.opencon, sql, "DataSiswa")
DataGridView1.DataSource = dssiswa
DataGridView1.DataMember = "DataSiswa"
DataGridView1.ReadOnly = True
ClassSiswa.closecon()
End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ExportExcel()
End Sub
Private Sub ExportExcel()
Dim xlApp As Microsoft.Office.Interop.Excel.Application
Dim xlBook As Microsoft.Office.Interop.Excel.Workbook
Dim xlSheet As Microsoft.Office.Interop.Excel.Worksheet
Dim oValue As Object = System.Reflection.Missing.Value
Dim sPath As String = String.Empty
Dim dlgSave As New SaveFileDialog
dlgSave.DefaultExt = "xls"
dlgSave.Filter = "Microsoft Excel|*.xls"
dlgSave.InitialDirectory = Application.StartupPath
If dlgSave.ShowDialog = Windows.Forms.DialogResult.OK Then
Try
xlApp = New Microsoft.Office.Interop.Excel.Application
xlBook = xlApp.Workbooks.Add(oValue)
xlSheet = xlBook.Worksheets("sheet1")
Dim xlRow As Long = 2
Dim xlCol As Short = 1
For k As Integer = 0 To DataGridView1.ColumnCount - 1
xlSheet.Cells(1, xlCol) = DataGridView1(k, 0).Value
xlCol += 1
Next
For k As Integer = 0 To DataGridView1.ColumnCount - 1
xlSheet.Cells(2, xlCol) = DataGridView1(k, 0).Value
xlCol += 1
Next
For i As Integer = 0 To DataGridView1.RowCount - 1
xlCol = 1
For k As Integer = 0 To DataGridView1.ColumnCount - 1
xlSheet.Cells(xlRow, xlCol) = DataGridView1(k, i).Value
xlCol += 1
Next
xlRow += 1
Next
xlSheet.Columns.AutoFit()
Dim sFileName As String = Replace(dlgSave.FileName, ".xlsx", "xlx")
xlSheet.SaveAs(sFileName)
xlBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlBook)
releaseObject(xlSheet)
MsgBox("Data successfully exported.", MsgBoxStyle.Information, "PRMS/SOB Date Tagging")
Catch
MsgBox(ErrorToString)
Finally
End Try
End If
End Sub
End Class
it work perfectly fine except when i exported the datagridview to excel the column header text in the datagridview is not exported to excel sheet only the gridview.
how do i make the coding to get the column header text to excel sheet?
I think you'll have to get the HeaderText from each column like this:
xlSheet.Cells(x,y).Value = DataGridView1.Columns(k).HeaderText
You would put this in your "k" loop. And then write it wherever you want in the file. x and y have to be the location where you write the header (maybe determined by k)
EDIT: writing the headers in first row of excel
For k As Integer = 0 To DataGridView1.ColumnCount - 1
xlSheet.Cells(1,k+1).Value = DataGridView1.Columns(k).HeaderText
Next

Why does calculated row in dataGridView not get saved when exporting as an Excel file?

The code I am working on loads an XML file into a dataTable and displays it in a dataGridView. I then average each column in the dataGridView and display them as a new row in the dataGridView. I then export the dataGridView as an Excel file, however it is does not include the added average row. Any input that is manually entered into the dataGridView does get saved in the export? I understand that with SQL databases, you must call an update on the dataGridView source. I am not quite sure what to do in this case. Any ideas on how I can get the changes to be saved?
Opens a XML file and loads it into dataGridView
Private Sub ExOpen_Click(sender As Object, e As EventArgs) Handles ExOpen.Click
' Uses a openFileDialog to find the file path for the file the user wishes to
' use. It then displays the path in a textBox. Load a DataTable with the
' information found in the XML file and then set it as the dataSource for the
' DataGridView()
OpenFileDialog1.FileName = Nothing
OpenFileDialog1.Filter = "XML|*.xml"
If OpenFileDialog1.ShowDialog = System.Windows.Forms.DialogResult.OK Then
lblExFile.Text = OpenFileDialog1.FileName
End If
Dim dtDataTbl As New System.Data.DataTable
Dim dsDataSet As New DataSet
For Each dtDataTbl In dsDataSet.Tables
dtDataTbl.BeginLoadData()
Next
Try
dsDataSet.ReadXml(lblExFile.Text)
For Each dtDataTbl In dsDataSet.Tables
dtDataTbl.EndLoadData()
Next
DataGridView1.DataSource = dtDataTbl
Catch
Finally
dsDataSet = Nothing
dtDataTbl = Nothing
End Try
End Sub
Performs average of columns and adds it as a new row in dataGridView
Private Sub ExAvg_Click(sender As Object, e As EventArgs) Handles ExAvg.Click
' Goes through each column and finds the average. The averages are printed out
' into the DataGridView.
Dim decAvg As Decimal = 0
Dim sValue As String = Nothing
Dim sAppend As String = Nothing
Dim iCount As Integer = 0
For iColumn As Integer = 1 To DataGridView1.Columns.Count - 1
iCount = 0
For iRow As Integer = 0 To DataGridView1.Rows.Count - 1
sAppend = Nothing
If Not DataGridView1.Rows(iRow).Cells(iColumn).Value Is Nothing Then
sValue = CStr(DataGridView1.Rows(iRow).Cells(iColumn).Value)
Dim cChars() As Char = sValue.ToCharArray()
' Each character is only taken if a digit or "."
For Each cCharacter In cChars
If Char.IsDigit(cCharacter) OrElse cCharacter = "." Then
sAppend &= cCharacter
End If
Next
iCount += 1
decAvg += CDec(sAppend)
End If
Next
decAvg = Math.Round(decAvg / iCount, 2)
' Print the average row in the DataGridView.
Try
If iColumn = 1 Then
DataGridView1.Rows(iCount).Cells(iColumn).Value = "$" & CStr(decAvg)
Else
DataGridView1.Rows(iCount).Cells(iColumn).Value = CStr(decAvg)
End If
DataGridView1.Rows(iCount).Cells(0).Value = "Average"
Catch
End Try
Next
DataGridView1.v()
End Sub
Exports the dataGridView as an Excel file(missing added average row)
Private Sub ExSave_Click(sender As Object, e As EventArgs) Handles ExSave.Click
' Information from the DataGridView is transferred into an excel object
' row by row and column by column. The file name is picked by the user
' using a saveFileDialog.
SaveFileDialog1.FileName = Nothing
SaveFileDialog1.Filter = "Excel File|*.xls"
If SaveFileDialog1.ShowDialog = System.Windows.Forms.DialogResult.OK Then
lblExFile.Text = SaveFileDialog1.FileName
End If
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = CType(xlWorkBook.Worksheets(1), Excel.Worksheet)
Dim dc As DataColumn
Dim dr As DataRow
Dim dt As System.Data.DataTable
dt = CType(DataGridView1.DataSource, System.Data.DataTable)
Dim colIndex As Integer = 0
Dim rowIndex As Integer = 0
Try
'Export the Columns to excel file
For Each dc In dt.Columns
colIndex = colIndex + 1
xlWorkSheet.Cells(1, colIndex) = dc.ColumnName
Next
'Export the rows to excel file
For Each dr In dt.Rows
rowIndex = rowIndex + 1
colIndex = 0
For Each dc In dt.Columns
colIndex = colIndex + 1
xlWorkSheet.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)
Next
Next
xlWorkSheet.Columns.AutoFit()
xlWorkBook.SaveAs(lblExFile.Text, XlFileFormat.xlWorkbookNormal, Type.Missing, _
Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlExclusive, _
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing)
xlWorkBook.Close()
You are adding the average to the GridView but write the datatable to Excel.

Export to excel vb.net

I have a problem when I export a flexgrid to excel from vb.net vs2008 to office 2010 english version an excel file is opened but it is empty. However, when I use office french version it is opened [correctly]
My code is:
On Error GoTo ErrorHandler
Dim iRow As Short
Dim iCol As Short
Dim objExcl As Excel.Application
Dim objWk As Excel.Workbook
Dim objSht As Excel.Worksheet
Dim iHead As Short
Dim vHead As Object
objExcl = New Excel.Application
objExcl.Visible = True
objExcl.UserControl = True
Dim oldCI As System.Globalization.CultureInfo = _
System.Threading.Thread.CurrentThread.CurrentCulture
System.Threading.Thread.CurrentThread.CurrentCulture = _
New System.Globalization.CultureInfo("en-US")
objWk = objExcl.Workbooks.Add
System.Threading.Thread.CurrentThread.CurrentCulture = oldCI
objSht = objWk.Sheets(1)
vHead = Split(g.FormatString, "|")
'populate heading in the sheet
'take the column heading from flex grid and put it in the sheet
For iHead = 1 To UBound(vHead)
If Len(Trim(vHead(iHead))) > 0 Then objSht.Cells._Default(1, iHead) = vHead(iHead)
Next
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor
For iRow = 0 To g.Rows - 1
For iCol = 0 To g.get_Cols() - 1
g.Row = iRow
g.Col = iCol
'
'If g.Text <> "" Then objSht.Cells._Default(iRow + 2, iCol + 1) = g.Text
If g.Text <> "" Then
objSht.Range(NumCol2Lattre(iCol + 1) & "" & iRow + 2 & ":" & NumCol2Lattre(iCol + 1) & "" & iRow + 2 & "").Select()
objExcl.ActiveCell.Value = g.Text
End If
Next iCol
Next iRow
objExcl.Application.Visible = True
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default
objSht = Nothing
objWk = Nothingl may not be destroyed until it is garbage collected. Click
objExcl = Nothing
Exit Sub
ErrorHandler:
objSht = Nothing
objWk = Nothing
objExcl = Nothing
MsgBox("Error In expotation task & " & Err.Description, MsgBoxStyle.Information)
Err.Clear()
Check out this website Exporting MSFlexGrid to Excel
I suspect your problem is with vHead = Split(g.FormatString, "|") Use the debugger to find out what is the value of g.FormatString. Is it causing an error? Step through the code one line at a time and see what happens.
On Error GoTo ErrorHandler
Imports System.Data
Imports System.IO
Imports System.Web.UI
Partial Class ExportGridviewDatainVB
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindGridview()
End If
End Sub
Protected Sub BindGridview()
Dim dt As New DataTable()
dt.Columns.Add("UserId", GetType(Int32))
dt.Columns.Add("UserName", GetType(String))
dt.Columns.Add("Education", GetType(String))
dt.Columns.Add("Location", GetType(String))
dt.Rows.Add(1, "SureshDasari", "B.Tech", "Chennai")
dt.Rows.Add(2, "MadhavSai", "MBA", "Nagpur")
dt.Rows.Add(3, "MaheshDasari", "B.Tech", "Nuzividu")
dt.Rows.Add(4, "Rohini", "MSC", "Chennai")
dt.Rows.Add(5, "Mahendra", "CA", "Guntur")
dt.Rows.Add(6, "Honey", "B.Tech", "Nagpur")
gvDetails.DataSource = dt
gvDetails.DataBind()
End Sub
Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
' Verifies that the control is rendered
End Sub
Protected Sub btnExport_Click(ByVal sender As Object, ByVal e As EventArgs)
Response.ClearContent()
Response.Buffer = True
Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", "Customers.xls"))
Response.ContentType = "application/ms-excel"
Dim sw As New StringWriter()
Dim htw As New HtmlTextWriter(sw)
gvDetails.AllowPaging = False
BindGridview()
'Change the Header Row back to white color
gvDetails.HeaderRow.Style.Add("background-color", "#FFFFFF")
'Applying stlye to gridview header cells
For i As Integer = 0 To gvDetails.HeaderRow.Cells.Count - 1
gvDetails.HeaderRow.Cells(i).Style.Add("background-color", "#df5015")
Next
gvDetails.RenderControl(htw)
Response.Write(sw.ToString())
Response.[End]()
End Sub
End Class