Tuesday, August 28, 2012

c# (c Sharp) wpf 2010 using Excel

c# (c Sharp) wpf 2010 using Excel, wpf 2010 using Excel
Code to access Excel File using c# wpf 2010


//Add reference to Microsoft.Office.Interop.Excel
//Goto Project->Add Reference->.NET and look for Microsoft.Office.Interop.Excel, then click OK

//Type reference to Excel

using Excel = Microsoft.Office.Interop.Excel;


//Type the code below on your trigger button
Excel.Application ExcelApp = new Excel.Application();

//To create a new Workbook
//Excel.Workbook WBook = ExcelApp.Workbooks.Add();

//To open existing workbook
//Here I'm opening an Excel File named Workbook.xlsx found on my bin/debug folder, inside "Excel Files" folder.

Excel.Workbook WBook = ExcelApp.Workbooks.Open(System.AppDomain.CurrentDomain.BaseDirectory + "Excel Files\\Workbook.xlsx", 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);


//To create a Sheets object that holds the Worksheets within the workbook
Excel.Sheets AllSheets = WBook.Worksheets;

//To read individual worksheet
Excel.Worksheet WSheets = (Excel.Worksheet)AllSheets.get_Item("Test_Sheet");
WSheets.Select();

//To display Excel Application while working
ExcelApp.Visible = true;

//Set the value of cell A1 to "www.kreativeidea21.blogspot.com"
WSheets.get_Range("A1", "A1").Value = "www.kreativeidea21.blogspot.com";


//Shows how to retrieve data from cell a1.
//A redline will appear under Message.Show, this is NOT an error.
MessageBox.Show(WSheets.get_Range("A1", "A1").Value);


MessageBox.Show("press any key to exit!");


//To save updated sheet
WBook.Save();

//To close sheet
WBook.Close();

//To free up memmory and close excel
ExcelApp.Quit();

0 comments: