Introduction
This is a test application which tells how to use the Microsoft Excel 10.0 Object Library to load/read Excel content.
Note: Here I have created a test.xls file which will be copied to c:\ before running the application.
The application is a Console Application developed using VC#.
Steps
- Include the following references to the project:
- Microsoft Excel 10.0 Object Library
- Microsoft Office 10.0 Object Library
- Include the required namespace:
using Excel;
. - Create the objects
ExcelApplicationClass
, WorkBook
, and Range
.
Here is the complete code:
using System;
using Excel;
namespace TestExcel
{
class ExcelApplication
{
[STAThread]
static void Main(string[] args)
{
string Path = @"c:\test.xls";
Excel.ApplicationClass app = new ApplicationClass();
Excel.Workbook workBook = app.Workbooks.Open(Path,
0,
true,
5,
"",
"",
true,
Excel.XlPlatform.xlWindows,
"\t",
false,
false,
0,
true,
1,
0);
Excel.Worksheet workSheet = (Excel.Worksheet)workBook.ActiveSheet;
int index = 0;
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);
}
}
}
}