Thursday, March 5, 2015

Extract From Excel File

// Row and Column Count is Start From 1  

private
List<long> SelectDefaultRouteClassByExcel()
{
    List<long> result = new List<long>();

    Excel.Application xlApp;
    Excel.Workbook xlWorkBook;
    Excel.Worksheet xlWorkSheet;
    Excel.Range range;

    int rowCnt = 0;

xlApp = new Excel.Application();

xlWorkBook = xlApp.Workbooks.Open("D:\\Load\\Route\\excelList.xlsx", 0, true, 5, "", "",      true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true,      1, 0);

    xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

    range = xlWorkSheet.UsedRange;

    for (rowCnt = 2; rowCnt <= range.Rows.Count; rowCnt++)
    {
        var hasObject = ((range.Cells[rowCnt, 3] as Excel.Range).Value2);

        if (hasObject != null)
        {
           long item = range.Cells[rowCnt, 3] as Excel.Range).Value2);
           result.Add(item);
         }
     }

       xlWorkBook.Close(true, null, null);
       xlApp.Quit();

       releaseObject(xlWorkSheet);
       releaseObject(xlWorkBook);
       releaseObject(xlApp);

       return result;
}


private void releaseObject(object obj)
{
Try
{
       System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
        obj = null;
     }
     catch (Exception ex)
     {
         obj = null;
         MessageBox.Show("Unable to release the Object " + ex.ToString());
      }
      finally
      {
          GC.Collect();
       }
}
----------------------------------

Date Time = DateTime.FromOADate(((range.Cells[rowCnt, 3] as Range).Value2))




No comments:

Post a Comment