Hello,
Rather than use Office automation, a cleaner method is to work with OpenXML for Excel using SpreadSheetLight which is a free library installed using NuGet package manager inside of Visual Studio.
The following code sample compiles as x86 or x64, uses a DataTable as the DataSource for a DataGridView (which is better than populating without a data source. Where the data comes from to populate is not a concern, could comes from a text file, tables in a database etc, all that matters is having the DataTable populated.
Full source can be found in the following GitHub repository so you can look at the code, if you decide to use the code copy and paste code into your project in regards to the file ExcelOperations.vb and install the required NuGet packages (there are instructions on the main page for this)
Backend class for Excel operation
Imports SpreadsheetLight
Public Class ExcelOperations
''' <summary>
''' Export a DataTable to Excel
''' </summary>
''' <param name="pFileName">path and file name to save too, path is optional</param>
''' <param name="pSheetName">Name of sheet</param>
''' <param name="pDataTable">Populated DataTable</param>
''' <param name="pColumnHeaders">True for column names as first row, false no column names</param>
Public Shared Sub SimpleExportRaw(pFileName As String, pSheetName As String, pDataTable As DataTable, pColumnHeaders As Boolean)
Using doc As New SLDocument()
doc.SelectWorksheet(pSheetName)
doc.ImportDataTable(1, SLConvert.ToColumnIndex("A"), pDataTable, pColumnHeaders)
Dim style As New SLStyle With {.FormatCode = "MM/dd//yyyy"}
' Format modified date column
doc.SetColumnStyle(11, style)
style.Font.Bold = True
doc.SetRowStyle(1, 1, style)
Dim stats = doc.GetWorksheetStatistics()
' auto fit all columns
doc.AutoFitColumn(1, stats.EndColumnIndex)
' original default name is Sheet1, let's change it to the name in pSheetName
doc.RenameWorksheet(SLDocument.DefaultFirstSheetName, pSheetName)
doc.SaveAs(pFileName)
End Using
End Sub
End Class
Button click event in form
Private Sub ExportToExcelButton_Click(sender As Object, e As EventArgs) Handles ExportToExcelButton.Click
Dim dt = CType(DataGridView1.DataSource, DataTable)
ExcelOperations.SimpleExportRaw("Customers.xlsx", "Customers", dt, True)
MessageBox.Show("Exported")
End Sub