Import Data from Excel to SQL Server Data in web servers, it's no need to install Microsoft Office software.

XsExcel SDK provides methods to import data from other data source, like Microsoft SQL Server database. Getting data table from sql database, and converting and inserting to worksheet. All the data type will keey the original data type in database.

This guide page provides C# users with how to import data from SQL database to XLSX and XLS spreadsheet with XsExcel SDK in C#.NET.


public static void ImportSqlTableToSheet()
{
    // Export data from sql database
    DataTable dt = getTableFromSqlServer();
    string filename = "DataTableSample.xlsx";

    // Create a new workbook
    Workbook workbook = new Workbook();
    // Import data table from sql to worksheet
    workbook.ConvertDataTableToSheet(dt);

    // Save and show the spreedsheet
    if (File.Exists(filename)) File.Delete(filename);
    workbook.Save(filename);
    Process.Start(filename);
}

private static DataTable getTableFromSqlServer()
{
    DataTable dt = null;
    string connString = @"Data Source=.;Initial Catalog=database name;Integrated Security=True";
    string query = "select * from table";

    SqlConnection conn = new SqlConnection(connString);
    SqlCommand cmd = new SqlCommand(query, conn);
    conn.Open();

    // create data adapter
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    // this will query your database and return the result to your datatable
    da.Fill(dt);
    conn.Close();
    da.Dispose();

    return dt;
}

Notice - If you used the trial version of XsExcel SDK, can only edit, insert or get the first 300 row data!

More Excel tutorial