rahul ahuja

rahul ahuja

  • NA
  • 80
  • 35.9k

Read Data from excel sheet using C# code

Sep 22 2015 8:23 AM
Hello All,
 I am getteing problem read data from the excel. I am using following code to read data from the excel, now  when code line "Excel.Workbook xlWorkbook = xlApp.Workbooks.Open("G:\\TestFiles\\Environment Data1.xls");"  open the excel file in background which i dont want to open that it should read data.
 
// Reference to Excel Application.
Excel.Application xlApp = new Excel.Application();
// Open the Excel file.
// You have pass the full path of the file.
// In this case file is stored in the Bin/Debug application directory.
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open("G:\\TestFiles\\Environment Data1.xls");
// Get the first worksheet.
Excel.Worksheet xlWorksheet = (Excel.Worksheet)xlWorkbook.Sheets.get_Item(1);
// Get the range of cells which has data.
Excel.Range xlRange = xlWorksheet.UsedRange;
// Get an object array of all of the cells in the worksheet with their values.
object[,] valueArray = (object[,])xlRange.get_Value(
Excel.XlRangeValueDataType.xlRangeValueDefault);
// iterate through each cell and display the contents.
for (int row = 1; row <= xlWorksheet.UsedRange.Rows.Count; ++row)
{
for (int col = 1; col <= xlWorksheet.UsedRange.Columns.Count; ++col)
{
// Print value of the cell to Console.
Console.WriteLine(valueArray[row, col].ToString());
}
}
// Close the Workbook.
xlWorkbook.Close(false);
// Relase COM Object by decrementing the reference count.
Marshal.ReleaseComObject(xlWorkbook);
// Close Excel application.
xlApp.Quit();
// Release COM object.
Marshal.FinalReleaseComObject(xlApp);
Console.ReadLine();

Answers (3)