четверг, 7 июня 2012 г.

Использование Excel в C#

Невозбранно потырил с http://blog.logiclabz.com/asp-net/reading-writing-data-from-excel-in-asp-net-2-0.aspx


  1. using Microsoft.Office.Interop.Excel;  
  2.   
  3. // Creates a new Excel Application Object  
  4. ApplicationClass xlsApp = new ApplicationClass();    
  5.   
  6. try  
  7. {  
  8.     //Opens WorkBook in Excel  
  9.     WorkbookClass xlsWrkBook=(WorkbookClass)xlsApp.Workbooks.Open  
  10.  ("c:\\1.xls", 0, false, 5, """"true,  
  11.  XlPlatform.xlWindows, "\t"falsefalse, 0, true, 1, 0);  
  12.     //Gets the sheet 1 of the opened workbook    
  13.     Worksheet xlsWrkSht = (Worksheet)xlsWrkBook.Worksheets.get_Item(1);  
  14.     //Gets Cell 1st Row and 1st Column. Desired can be given   
  15.     Range ExcelCellText = (Range)xlsWrkSht.Cells[1, 1];  
  16.     // Reads Data of selected cell  
  17.     string str = ExcelCellText.Text.ToString();  
  18.     // Writes Data of selected cell   
  19.     ExcelCellText.Value2 = "Sample Write";  
  20.     xlsWrkBook.Save();  
  21.     xlsWrkBook.Close(0, 0, 0);  
  22. }  
  23.   
  24. catch  
  25. { }  
  26.   
  27. finally  
  28. {  
  29.     xlsApp = null;  
  30. }