Automating excel

I hope this article will help the novice in .net. This is article which will help you for Excel automation.

For this automation process we need to follow the below steps

1. Add a reference to the Microsoft Excel object library COM component.
2. Add the namespace Excel
3. Instantiate the class Excel.ApplicationClass as below

Excel.Application xl=new Excel.ApplicationClass();
4. To open an excel file,

Excel.Workbook wb=xl.Workbooks.Open(Environment.CurrentDirectory+"/SampleExcel.xls",0, false, 5, System.Reflection.Missing.Value, System.Reflection.Missing.Value, false, System.Reflection.Missing.Value, System.Reflection.Missing.Value,true, false, System.Reflection.Missing.Value, false, false, false);
//Open the excel sheet

5. To read cell(s) in the worksheet,

Excel.Sheets xlsheets=wb.Sheets;
 //Get the sheets from workbook
Excel.Worksheet excelWorksheet = (Excel.Worksheet)xlsheets[1];
 //Select the first sheet
Excel.Range excelCell = (Excel.Range)excelWorksheet.get_Range("B4:FZ4",Type.Missing);
 //Select a range of cells
Excel.Range excelCell2 = (Excel.Range)excelWorksheet.get_Range("A5:A5",Type.Missing);
//Select a single cell
Console.WriteLine(excelCell2.Cells.Value2.ToString());
 //Print the value of the cell for a single cell selection
System.Array myvalues = (System.Array)excelCell.Cells.Value2;
//Assign it to an array
string[] strArray = ConvertToStringArray(myvalues);
//Convert array into String array
foreach (string str in strArray)
Console.WriteLine(" Text in Cell " + str);
 //Loop through the array to print the values in the cell

By alice johnson   Popularity  (5970 Views)