.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Code Snippets >> File Operation >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Read data from excel using c#

Posted By:Deco       Posted Date: October 27, 2010    Points: 15    Category: File Operation    URL: http://www.dotnetspark.com  

This article will help you to load the excel file data through c# code.
 

1. Include the following reference into the project : 

Microsoft Excel 10.0 Object Library 

Microsoft Office 10.0 Object Library 

2. Include the name space i.e. using Excel. 

3. Creating the ExcelApplicationClass,WorkBook and Range.

Find the complete code below:

using System;
using Excel;
namespace TestExcel
{
class ExcelApplication
{
[STAThread]
static void Main(string[] args)
{

string Path = @"c:\test.xls";
// initialize the Excel Application class
Excel.ApplicationClass app = new ApplicationClass();
// create the workbook object by opening  the excel file.
Excel.Workbook workBook = app.Workbooks.Open(Path,
0,
true,
5,
"",
"",
true,
Excel.XlPlatform.xlWindows,
"\t",
false,
false,
0,
true,
1,
0);
// Get The Active Worksheet Using Sheet Name Or Active Sheet
Excel.Worksheet workSheet = (Excel.Worksheet)workBook.ActiveSheet;
int index = 0;
// This row,column index should be changed as per your need.
// that is which cell in the excel you are interesting to read.
object rowIndex = 2;
object colIndex1 = 1;
object colIndex2 = 2;
try
{
while ( ((Excel.Range)workSheet.Cells[rowIndex,colIndex1]).Value2 != null )
{
rowIndex = 2+index;
string firstName = ((Excel.Range)workSheet.Cells[rowIndex,colIndex1]).Value2.ToString();
string lastName = ((Excel.Range)workSheet.Cells[rowIndex,colIndex2]).Value2.ToString();
Console.WriteLine("Name : {0},{1} ",firstName,lastName);
index++;
}
}
catch(Exception ex)
{
app.Quit();
Console.WriteLine(ex.Message);
}
}

}
}

     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend