Microsoft Office Tutorials and References
In Depth Information
Connecting with Microsoft SQL Server 2008 database
{
// Opening SQL connection for Microsoft SQL Server 2008
// WINNER the database server contains the databse called Products
SqlConnection MySQLConnection = new SqlConnection(@"Data
Source=WINNER;Initial Catalog=Products;
Integrated Security=True");
// Passing SQL command text
SqlCommand MySQLCommand = new SqlCommand("SELECT * FROM
Books", MySQLConnection);
MySQLConnection.Open();
// SQL reader to read through data from Database
SqlDataReader MySQLReader = MySQLCommand.ExecuteReader();
// Get the active sheet of current application
Excel.Worksheet MyWorkSheet = this.Application.ActiveSheet as
Excel.Worksheet;
// Header for the columns set in the Value2 properties
((Excel.Range)MyWorkSheet.Cells[1, 1]).Value2 = "Book Name";
((Excel.Range)MyWorkSheet.Cells[1, 2]).Value2 = "Author Name";
// Indexer
int i = 2;
// Loop to read through the database returned data
while (MySQLReader.Read())
{
// Writing the data from the database table column BookName
((Excel.Range)MyWorkSheet.Cells[i, 1]).Value2 =
MySQLReader["BookName"];
// Writing the data from the database table column Author
((Excel.Range)MyWorkSheet.Cells[i, 2]).Value2 =
MySQLReader["Author"];
i++;
}
// Dispose the SQL command
MySQLCommand.Dispose();
// Closing SQL connection after using it.
MySQLConnection.Close();
}
The following screenshot displays data retrieved from Microsoft SQL Server 2008
database and the data being displayed in the worksheet cells.
 
Search JabSto ::




Custom Search