Page 1 of 1

Excel data into C# array?

Posted: July 26th, 2005, 9:23 pm
by European81
Is it possible to get data from an Excel workbook into a C# array? Much data material comes on the form of an excel file so such an option would be very useful.

Excel data into C# array?

Posted: August 10th, 2005, 5:18 am
by alvincho
I copied the following from my blog: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/deta ... nMicrosoft 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);And Excel.Workbook theWorkbook = ExcelObj.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.