C#

usingSystem.Data;usingSystem.Data.SqlClient;usingSystem.Windows.Forms;usingSystem.Xml;usingMicrosoft.Office.Tools.Ribbon;usingMicrosoft.Office.Interop.Excel;//last line very important,do not confused with Microsoft.Office.Tools.Excel;privatevoidbuttonImportFromSql_Click(objectsender,RibbonControlEventArgse){varsheet=(Microsoft.Office.Interop.Excel.Worksheet)Globals.ThisWorkbook.ActiveSheet;PopulateData(sheet);}privatevoidPopulateData(Worksheetsheet){try{stringsheetName=sheet.Name;SqlConnectionconn=newSqlConnection("Integrated Security=yes;Initial Catalog=RpoPrTracker;Data Source=(local)");conn.Open();SqlCommandcommand=newSqlCommand(string.Format("select * from {0}",sheetName),conn);SqlDataAdapteradapter=newSqlDataAdapter(command);DataSetdataset=newDataSet();adapter.Fill(dataset);System.Data.DataTabletable=dataset.Tables[0];intColumnIndex=0;sheet.Cells.ClearContents();foreach(System.Data.DataColumncolintable.Columns){ColumnIndex++;sheet.Cells[1,ColumnIndex]=col.ColumnName;}introwIndex=0;foreach(DataRowrowintable.Rows){rowIndex++;ColumnIndex=0;foreach(DataColumncolintable.Columns){ColumnIndex++;sheet.Cells[rowIndex+1,ColumnIndex]=row[col.ColumnName];}}}catch(XmlExceptionexml){// catch an xmlexception errorsMessageBox.Show(exml.Message);}}