1, note:
First, add a com reference to the image. Right-click references => Add reference => COM => and add Microsoft Excel 11.0 Object Library.
2,ProgramExample:
Using System. Data;
Using Excel = Microsoft. Office. InterOP. Excel; // Excel is used as an alias to facilitate program reference.
Namespace Test
{
Public Class _ Test
{
Private Datatable readfromxls ( String S_filename)
{
Datatable dttemp = New Datatable ();
Datacolumn column;
Column = New Datacolumn ( " Ms_part " );
Dttemp. Columns. Add (column );
Column = New Datacolumn ( " Part_desc " );
Dttemp. Columns. Add (column );
Column = New Datacolumn ( " Type " );
Dttemp. Columns. Add (column );
Column = New Datacolumn ( " Status " );
Dttemp. Columns. Add (column );
Excel. Application m_xlsapp = Null ;
Excel. Workbook m_workbook = Null ;
Excel. worksheet m_worksheet = Null ;
Excel. Range m_rangemspart = Null ;
Excel. Range m_rangepartdesc = Null ;
Excel. Range m_rangetype = Null ;
Excel. Range m_rangestatus = Null ;
Try
{
Object Objopt = System. reflection. Missing. value;
M_xlsapp = New Excel. Application ();
M_workbook = Values (s_filename, objopt, objopt );
M_worksheet = (Excel. worksheet) m_workbook.worksheets.get_item ( 1 );
Datarow newrow;
For ( Int I = 1 ; I <= M_worksheet.usedrange.rows.count; I ++ )
{
// This method can also be used to obtain cells.
// M_rangemspart = (Excel. Range) m_worksheet.cells [I, 1];
// M_rangepartdesc = (Excel. Range) m_worksheet.cells [I, 2];
// M_rangetype = (Excel. Range) m_worksheet.cells [I, 3];
// M_rangestatus = (Excel. Range) m_worksheet.cells [I, 4];
M_rangemspart = M_worksheet.get_range ( " A " + I. tostring (), objopt );
M_rangepartdesc = M_worksheet.get_range ( " B " + I. tostring (), objopt );
M_rangetype = M_worksheet.get_range ( " C " + I. tostring (), objopt );
M_rangestatus = M_worksheet.get_range ( " D " + I. tostring (), objopt );
Newrow = Dttemp. newrow ();
Newrow [ " Ms_part " ] = M_rangemspart.value2.tostring ();
Newrow [ " Part_desc " ] = M_rangepartdesc.value2.tostring ();
Newrow [ " Type " ] = M_rangetype.value2.tostring ();
Newrow [ " Status " ] = M_rangestatus.value2.tostring ();
Dttemp. Rows. Add (newrow );
}
}
Catch (Exception exc)
{
ThrowExc;
}
Finally
{
M_xlsapp.quit ();
M_xlsapp= Null;
}
Return Dttemp;
}
}
}