Here, I will explain how to export data from a database to an Excel file in the Window form. So, I suggest you, before coming to this tutorial you read the Tutorial 28.
Step 1: Form
In tutorial 14 I showed you how to show a data in the DataGridView from the database. Here, I will show you that data in the Excel File.
Step 2: Load the data into the Data Grid View from the database.
Click on the Load button and write the code to load the data. For this code, you may Go on to my tutorial 14.
Step 3: Code
In Tutorial 28 I showed you How to create an Excel sheet, so I suggest you before coming on this tutorial, you go on to Tutorial 28.
Here, we will add two more Namespace.
using ExcelLibrary.BinaryDrawingFormat;
using ExcelLibrary.BinaryFileFormat;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using ExcelLibrary.CompoundDocumentFormat;
using ExcelLibrary.SpreadSheet;
using ExcelLibrary.BinaryDrawingFormat;
using ExcelLibrary.BinaryFileFormat;
using System.Text;
using System.IO;
namespace First_Csharp_app
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Load_button_Click(object sender, EventArgs e)
SqlConnection con = new SqlConnection("server = MUNESH;Database=datastore;UID=sa;Password=123;");
SqlCommand cmd = new SqlCommand("Select ID,Name,SurName,Age, from data1", con);
try
{
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
BindingSource bsource = new BindingSource ();
bsource .DataSource = dt;
dataGridView1.DataSource = bsource ;
da.Update(dt);
DataSet ds = new DataSet("New_DataSet");
ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
da.Fill( dt );
ds.Tables.Add( dt );
ExcelLibrary. DataSetHelper.CreateWorkBook("MyFirstExcelSheet.xls" ,ds);
}
catch (Exception ec)
{
MessageBox.Show(ec.Message);
}
}
}
Step 4: Output
Run your application and click on the load event.