Introduction
This is project will be very easy to know about how to create a new excel file and how to insert data into excel cell.To do this we need to add reference to the Microsoft Excel.dll. To add reference right click on references in solution explorer->select add references->select com tab -> select microsoft excel.dll. And one more main thing is normally we will get one exception error call "old format or invalid type library". This code will solve that problem also. I have attached the complete code with comments of my application here.
The following code will come in the code view of the the Form1. This form will contain a single command button. During the click event of this button it ll retrieve the data from table and it ll insert that into Excel cells.
DatabaseToExcel.DB objDB;
Excel.Application application;
Excel.Workbook book;
Excel.Worksheet sheet;
string query = "select * from TestExcel";
string ConnectionString = "server=FARQUI;database=sample;uid=sa;pwd=;";
private void Form1_Load(object sender, System.EventArgs e)
{
application = new Excel.ApplicationClass();
System.Globalization.CultureInfo oldCI =
System.Threading.Thread.CurrentThread.CurrentCulture ;
System.Threading.Thread.CurrentThread.CurrentCulture =
new System.Globalization.CultureInfo("en-US");
book = application.Workbooks.Add(Type.Missing);
application.Visible = true;
}
private void cmd_create_Click(object sender, System.EventArgs e)
{
try
{
DataTable dt = new DataTable();
objDB = new DatabaseToExcel.DB(ConnectionString);
dt = objDB.runQuery(query);
ctl_progress.Visible = true;
ctl_progress.Minimum = 1;
ctl_progress.Maximum = dt.Rows.Count + 1;
ctl_progress.Value = 1;
sheet = (Excel.Worksheet)book.Worksheets[1];
sheet.Name = "SampleExcel";
for(int i = 1 ; i <= dt.Rows.Count ; i++)
{
for(int j = 1 ; j <= dt.Columns.Count ; j++ )
{
((Excel.Range)sheet.Cells[i,j]).Value2
= dt.Rows[i-1].ItemArray[j-1].ToString();
}
ctl_progress.Value += 1;
}
MessageBox.Show("Your Process Completed Successfully");
ctl_progress.Visible = false;
}
catch(Exception e1)
{
MessageBox.Show(e1.Message);
}
}
The following code is my DB.cs class. This is for handling database functions.
using System;
using System.Data;
using System.Data.SqlClient;
namespace DatabaseToExcel
{
public class DB
{
string ConnectionString;
SqlConnection con;
public DB(string s)
{
ConnectionString = s;
con = new SqlConnection(ConnectionString);
}
public DataTable runQuery(string query)
{
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(query,con);
da.Fill(dt);
return dt;
}
}
}