Showing posts with label Excell. Show all posts
Showing posts with label Excell. Show all posts

Reading Excel files from .NET/C#

First you must declare using namespace


using Microsoft.Office.Interop.Excel;
if the Office Primary Interop Assemblies is installed in your system. If not, you can get it at http://www.microsoft.com/downloads/details.aspx?FamilyId=C41BD61E-3060-4F71-A6B4-01FEBA508E52&displaylang=en

Microsoft has changed the design of Office Primary Interop Assemblies in Office 2003. So if you want to read Excel files from a system with Office 2002 or before, you must use:

   Excel.Application excel = new Excel.Application();

Excel.Workbook theWorkbook = excel.Workbooks.Open(
FileName,,Missing.Value,Missing.Value,Missing.Value,Missing.Value,
Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,
Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value);
You can't use null as parameters, that will cause an exception.

in Office 2003, Excel is just a namespace and everything has a Class postfix:


ApplicationClass excel=new ApplicationClass();

Workbook theWorkbook = excel.Workbooks.Open(
FileName,,Missing.Value,Missing.Value,Missing.Value,Missing.Value,
Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,
Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value);

After you open the workbook, you can use the following codes to get data into your memory:

ws=(Worksheet)wb.Sheets[1];
r=ws.get_Range("B3","K100");
values=(object[,])r.Value2;
the Range.Value2 return a 2-dimension array of object. The first represents rows and the second represents columns. For example, if you want to get the value in B10, which is the 8-th row and the first column is return range r. You can use

v=values[8,1].ToString();
to get the value. You will know many features in Excel COM Model are missing in the .NET imlementation.

Source : http://blog.jumbosoft.com/alvincho/PermaLink,guid,77f86a28-206f-4474-b12b-1fcc6160a286.aspx

0 comments