Paperwork

5 Ways to Insert Data in Excel with VB.NET

5 Ways to Insert Data in Excel with VB.NET
How To Insert Data In Excel Sheet Using Vb.net

Whether you're handling a large dataset or looking to automate the process of data manipulation, Microsoft Excel paired with VB.NET can provide robust solutions to manage your data effectively. This blog post will explore five comprehensive ways to insert data into Excel using VB.NET, ensuring you have the tools to streamline your workflow or automate your data entries seamlessly.

1. Using Excel Interop

Arrays Vb Net Excel Application Get Showing Values Of An Range

VB.NET’s interoperability with Excel allows developers to control Excel through code. This method involves:

  • Adding the Microsoft.Office.Interop.Excel assembly reference.
  • Creating an instance of the Excel application.
  • Manipulating Excel cells and workbooks programmatically.
Imports Microsoft.Office.Interop.Excel

Public Sub InsertDataUsingInterop()
    Dim excelApp As New Application
    Dim workbook As Workbook = excelApp.Workbooks.Add()
    Dim worksheet As Worksheet = workbook.Worksheets(1)

    worksheet.Cells(1, 1) = "Name"
    worksheet.Cells(1, 2) = "Age"
    worksheet.Cells(1, 3) = "City"

    Dim data As Object(,) = {{"John", 30, "New York"}, {"Alice", 25, "Chicago"}}
    worksheet.Range("A2").Resize(data.GetLength(0), data.GetLength(1)).Value = data

    workbook.SaveAs("C:\MyExcelFile.xlsx")
    workbook.Close()
    excelApp.Quit()

    ' Release COM Objects
    System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet)
    System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook)
    System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp)
    worksheet = Nothing
    workbook = Nothing
    excelApp = Nothing
End Sub

⚠️ Note: Remember to release COM objects to avoid Excel instances remaining in memory.

2. Utilizing ExcelDataReader

How To Insert Multiple Rows In Excel The Simplest Way Youtube

This library simplifies reading Excel files but can also be used for writing data:

  • Install the ExcelDataReader package via NuGet.
  • Read and write data using DataSet or data streams.
Imports ExcelDataReader

Public Sub InsertDataUsingExcelDataReader()
    Dim fileToPath = "C:\MyExcelFile.xlsx"
    Dim stream As New FileStream(fileToPath, FileMode.Open, FileAccess.Read)

    Dim reader As ExcelReaderFactory = ExcelReaderFactory.CreateReader(stream)
    Dim dataSet As DataSet = reader.AsDataSet

    Dim table As DataTable = dataSet.Tables(0)
    Dim row As DataRow = table.NewRow()
    row.ItemArray = New Object() {"Jane", 35, "Seattle"}
    table.Rows.Add(row)

    Dim result As New FileInfo(fileToPath)
    Using fs = New FileStream(result.FullName, FileMode.Create, FileAccess.Write)
        dataSet.WriteXml(fs, XmlWriteMode.WriteSchema)
    End Using
End Sub

3. Using ADO.NET OLEDB

How To Export From Datagridview To Excel In Vb Net

ADO.NET provides a way to work with various data sources including Excel files:

  • Establish a connection to the Excel file via OLEDB.
  • Use SQL commands to manipulate data.
Imports System.Data.OleDb

Public Sub InsertDataUsingOLEDB()
    Dim connectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\MyExcelFile.xlsx;Extended Properties='Excel 12.0 Xml;HDR=YES'"
    Dim conn As New OleDbConnection(connectionString)

    Dim cmd As New OleDbCommand("INSERT INTO [Sheet1$] (Name, Age, City) VALUES (@Name, @Age, @City)", conn)

    conn.Open()
    
    cmd.Parameters.AddWithValue("@Name", "Sam")
    cmd.Parameters.AddWithValue("@Age", 40)
    cmd.Parameters.AddWithValue("@City", "San Francisco")
    cmd.ExecuteNonQuery()
    
    conn.Close()
End Sub

4. EPPlus

Excel 2007 How To Add Data In Excel Spreadsheet Youtube

EPPlus offers a wide range of functionalities without the need for Excel to be installed on the machine:

  • Install EPPlus from NuGet.
  • Manipulate workbooks, sheets, and cells directly from code.
Imports OfficeOpenXml

Public Sub InsertDataUsingEPPlus()
    Dim fileInfo As New FileInfo("C:\MyExcelFile.xlsx")
    Using package As New ExcelPackage(fileInfo)
        Dim worksheet As ExcelWorksheet = package.Workbook.Worksheets(1)
        
        worksheet.Cells("A" & (worksheet.Dimension.End.Row + 1)).Value = "Mark"
        worksheet.Cells("B" & (worksheet.Dimension.End.Row)).Value = 32
        worksheet.Cells("C" & (worksheet.Dimension.End.Row)).Value = "Boston"
        
        package.Save()
    End Using
End Sub

5. ClosedXML

How To Excel Chart In Vb Net Picture Box

Another open-source library, ClosedXML, allows for manipulation of Excel files:

  • Install ClosedXML via NuGet.
  • Work with Excel in an object-oriented manner.
Imports ClosedXML.Excel

Public Sub InsertDataUsingClosedXML()
    Dim workbook As New XLWorkbook()
    Dim worksheet = workbook.Worksheets.Add("Data")

    worksheet.Cell(1, 1).Value = "Name"
    worksheet.Cell(1, 2).Value = "Age"
    worksheet.Cell(1, 3).Value = "City"

    Dim data = New List(Of (String, Integer, String)) From {
        ("Lily", 28, "Portland"),
        ("Evan", 33, "Miami")
    }

    Dim row As Integer = 2
    For Each item In data
        worksheet.Cell(row, 1).Value = item.Item1
        worksheet.Cell(row, 2).Value = item.Item2
        worksheet.Cell(row, 3).Value = item.Item3
        row += 1
    Next

    workbook.SaveAs("C:\MyExcelFile.xlsx")
End Sub

In summary, these methods provide varying levels of control and dependency on Microsoft Excel itself. From using Excel Interop for full integration to leveraging third-party libraries like EPPlus and ClosedXML for powerful, install-free solutions, each approach has its place. Depending on your project requirements, you can choose the most fitting technique to insert data into Excel using VB.NET. Remember, while automation is key to efficiency, maintaining readability, ensuring data integrity, and optimizing code for SEO can help make your software solutions more accessible and efficient for end-users.

What is the difference between Excel Interop and other libraries?

Vb Net Tutorial How To Fill Datagridview From Two Sheets In Excel Using
+

Excel Interop requires Excel to be installed on the machine where the application is running, whereas libraries like EPPlus or ClosedXML do not have this dependency.

Can I use these methods to modify data in an existing Excel file?

Excel Insert Data In Excel Tutorial Desk
+

Yes, all methods outlined can be used for both reading and modifying data in existing Excel files.

Is there a performance impact when using these methods?

Reading And Writing An Excel File Using Vb Net Codeproject
+

Excel Interop can be slower due to the overhead of interacting with Excel directly. Libraries like EPPlus or ClosedXML are generally faster as they work on the file level.

Related Articles

Back to top button