DEV Community

IronSoftware
IronSoftware

Posted on • Originally published at ironsoftware.com

Load Excel From SQL Database (Code Example)

IronXL allows us create an Excel workbook from the SQL DataSet using System.Data.

C#:

using System.Data;
using System.Data.SqlClient;
using IronXL;

//Your sql query
string sql = "SELECT * FROM Users";

//Your connection string
string connectionString = @"Data Source=.\SQLEXPRESS;Initial Catalog=usersdb;Integrated Security=True";

using (SqlConnection connection = new SqlConnection(connectionString))
{
    //Open connections to the database
    connection.Open();
    SqlDataAdapter adapter = new SqlDataAdapter(sql, connection);
    DataSet ds = new DataSet();
    // Fill DataSet with data
    adapter.Fill(ds);


    //Create an Excel workbook from the SQL DataSet in one line
    WorkBook workbook = WorkBook.Load(ds);
}
Enter fullscreen mode Exit fullscreen mode

VB:

Imports System.Data
Imports System.Data.SqlClient
Imports IronXL

'Your sql query
Private sql As String = "SELECT * FROM Users"

'Your connection string
Private connectionString As String = "Data Source=.\SQLEXPRESS;Initial Catalog=usersdb;Integrated Security=True"

Using connection As New SqlConnection(connectionString)
    'Open connections to the database
    connection.Open()
    Dim adapter As New SqlDataAdapter(sql, connection)
    Dim ds As New DataSet()
    ' Fill DataSet with data
    adapter.Fill(ds)


    'Create an Excel workbook from the SQL DataSet in one line
    Dim workbook As WorkBook = WorkBook.Load(ds)
End Using
Enter fullscreen mode Exit fullscreen mode

Top comments (0)