Monday, August 25, 2014

Excel: Write to / Read From Cells

After I explained in the previous posts, how to include Excel in C#, how to create a new document or how to open one, I today want to show, how one can access the contents of the documents. This is pretty easy, via the property Range of an ExcelWorksheet one can access the single cells. The desired cell is either selected by specifying Row,Column or, like in Excel, by LetterNumber. Via the property Value then the content of the cell can be accessed. Note that Value contains a string, if the cell contains text, or a double, if the cell contains a number.
The following code creates a new Excel file, writes text in the cells 2,1 and B4, and eventually reads out the content of B4:

            Microsoft.Office.Interop.Excel.Application ExcelApp;
            Workbook ExcelWorkbook;
            Worksheet ExcelWorksheet;

            ExcelApp = new Microsoft.Office.Interop.Excel.Application();
            ExcelWorkbook = ExcelApp.Workbooks.Add();
            ExcelWorksheet = (Worksheet)ExcelWorkbook.Worksheets.get_Item(1);

            ExcelWorksheet.Cells[2, 1].Value = "Cell 2-1";
            ExcelWorksheet.Range["B4"].Value = "Cell B4";

            string Read = ExcelWorksheet.Range["B4"].Value;

            ExcelWorkbook.SaveAs("MyFirstExcelSheet.xls");
            ExcelWorkbook.Close();
            ExcelApp.Quit();

No comments:

Post a Comment